website/blog/2023-10-24-how-relay-enables-optimal-data-fetching.mdx
Relay’s approach to application authorship enables a unique combination of optimal runtime performance and application maintainability. In this post I’ll describe the tradeoffs most apps are forced to make with their data fetching and then describe how Relay’s approach allows you to sidestep these tradeoffs and achieve an optimal outcome across multiple tradeoff dimensions.
In component-based UI systems such as React, one important decision to make is where in your UI tree you fetch data. While data fetching can be done at any point in the UI tree, in order to understand the tradeoffs at play, let’s consider the two extremes:
Where in the UI tree you fetch data impacts multiple dimensions of the performance and maintainability of your application. Unfortunately, with naive data fetching, neither extreme is optimal for all dimensions. Let’s look at these dimensions and consider which improve as you move data fetching closer to the leaves, vs. which improve as you move data fetching closer to the root.
Relay leverages GraphQL fragments and a compiler build step to offer a more optimal alternative. In an app that uses Relay, each component defines a GraphQL fragment which declares the data that it needs. This includes both the concrete values the component will render as well as the fragments (referenced by name) of each direct child component it will render.
At build time, the Relay compiler collects these fragments and builds a single query for each root node in your application. Let’s look at how this approach plays out for each of the dimensions described above:
As you can see, Relay’s use of a declarative composable data fetching language (GraphQL), combined with a compiler step, allows us to achieve optimal outcomes across all of the tradeoff dimensions outlined above:
| Leaf node | Root node | GraphQL/Relay | |
|---|---|---|---|
| Loading experience | 🚫 | ✅ | ✅ |
| Suspense cascades | 🚫 | ✅ | ✅ |
| Composability | ✅ | 🚫 | ✅ |
| Granular updates | ✅ | 🚫 | ✅ |