Suspense Plus GraphQL
Published ....
Last modified ....
Share this post on BlueskySee discussion on Bluesky
Collocating GraphQL queries with components doesn't mean that you need to fetch data for every component in your app separately.
One of the greatest features of adopting GraphQL in my opinion has been the drive to colocate data requirements with the components that render that data, this collocation has cut down on the hard split of container and presentational components and has made it easier to develop features and applications in small units of code (aka components).
One of the fears about this collocation of data fetching with components that i have heard a few coworkers discuss has been the idea that having a lot of components do data fetching all by themselves could lead to a lot of loading spinners on the application during initial load. This fear derives from the idea that if every component needs to fetch its own data then we would have hundreds of components kicking of an Ajax request and we would have to wait for all the requests to resolve before showing the whole application as it is meant to be shown to the user.
I think there are two pretty simple ways to get over this fear, the first is easy to accomplish today, and the second is how I see the future of collocated data queries with components evolving to. Both of these examples are tightly coupled to React and GraphQL libraries like Apollo, but could probably be adopted by other view and data fetching libraries soon enough.
Current Day Resolved Data Fetching
The current day pattern to get over the need for showing a lot of spinners for each component that needs to fetch data is to export the data requirement from each component as a GraphQL fragment that a parent can import and resolve in a large query.
This pattern would look something like this: