Hello folks!
I’m new to GraphQL and was wondering what the best approach is for building a screen in React. Should I go with one big query or split it into multiple GraphQL queries? Thanks in advance!
Hello folks!
I’m new to GraphQL and was wondering what the best approach is for building a screen in React. Should I go with one big query or split it into multiple GraphQL queries? Thanks in advance!
Hello @LelouchRevolution,
When it comes to GraphQL, there are a few common strategies to build a screen in React. Each one has trade-offs depending on your use case:
1. Batch GraphQL operations
This is a middle ground where multiple queries are sent in a single HTTP request (batching).
This helps reduce network overhead compared to multiple requests, but:
Important:
If you’re using Apollo Client / Apollo Server, you’re covered, since Apollo supports batching (with proper setup).
2. Multiple requests
Here, you split your data fetching into separate queries. The advantage is:
But there’s an important downside when it comes to scale:
For example:
That’s 1 million requests per day just for a single screen, which can put significant pressure on your backend, gateways, and network.
Other downsides:
3. Big query (single request) + @defer
This is usually the best approach.
You fetch everything the screen needs in one GraphQL query, which gives you:
The classic downside is that the response waits for the slowest field. For example, with me, products, and cart:
me takes ~1sproducts takes ~2scart takes ~3sWithout @defer, the full response would only arrive after 3 seconds.
But with @defer, you can keep a single request and receive multiple incremental responses:
me arrives first (~1s)products next (~2s)cart last (~3s)This allows progressive rendering while keeping all the benefits of a single query.
Example using @defer
query HomeScreenQuery {
... @defer {
me {
id
name
}
}
... @defer {
featuredProducts {
id
title
products {
id
name
image
price
}
}
}
... @defer {
cart {
id
total
items {
id
quantity
price
}
}
}
}
With this:
Important:
@defer for this to workAgain, if you’re using Apollo Client / Apollo Server, they provide support for @defer (with proper configuration).
Fragment colocation (highly recommended)
When working with big queries, a really good pattern is fragment colocation:
This keeps your code modular, scalable, and easier to maintain as your app grows.
Good reference:
That article uses GraphQL Code Generator, but it’s worth noting:
useFragment from codegenuseFragment isn’t really a hook anywayThis post explains the discussion about Apollo and Codegen regarding fragments:
Wow Thank you so much! I really appreciate your time in make this detailed response.
I had never heard of the @defer directive. Thanks a lot! I just read more about it, and it seems awesome. Also, the concept of fragment colocation looks really interesting.