GraphQL makes it easy to get exactly the data we need for a given component. There are many times when we end up using the same query or part of a query in multiple places. This is where GraphQL Fragments can help us.
To declare a fragment we can add fragment MyAwesomeFragment on BlogPost. The keyword fragment tells GraphQL that we’re creating the fragment with the name, MyAwesomeFragment. And all of this is on the type BlogPost.
In this site I have a few different places where I’m querying images for galleries. So instead of repeating the whole query in every variation across the site I can create a queries file and drop the repeated parts in there. Here’s an example of that in action.
Then we can use them in our components with a page query or static query.
If you’re using TypeScript you can also drop the types for the fragments in the queries file so they’re all together.
Add an alias if you’re doing similar top level requests. Here’s an example of my Instagram requests.