For example, you have multiple components that might have a button. Rather than writing out that button several times, and potentially any logic around it, you could separate that as its own component and import it everywhere needing a button.
Ok, I think I got a little side-tracked with that explanation. Lets get back to those fragments!
Fragments are a fantastic way of breaking down large queries into smaller, more digestible chunks. This is great for a few reasons.
Large queries are difficult to read and a bit intimidating. Breaking them down makes it easier for you and another developer on the team to see whats going on.
If you have a group of fields that are repeated a few times, you can reduce duplication of code by using a fragment
Update one section of code to update everywhere. Meaning less chance of errors.
Lets take a look at a before and after of how fragments could be used.
Here is a simple query with two components that both contain the same fields for a button.
Nothing to crazy there, but now lets look at how using a fragment could improve this.
A big improvement to a small query. Now picture a full page query with multiple components. Yikes! We can use this same method to break that down into smaller, more maintable chunks.
Time for some more examples. Check out this page query loading a few different components.
I'm already getting nervous looking at this and it isn't even that big of a query! So lets take a look at how we can break this down into fragments. Here is a example of one of the components as its own fragment.
Beautful. Nice and simple. Easy to understand what's going on. Now lets look at what the main page query could look like when each component has been separated into fragments.
We have reduced a 41 line query to 13 lines by splitting sections into fragments. Making the main query easier to read and more maintanable.
Storing the fragments in different files
I like to store each fragment within its own file and import it into whichever file I have the main query.
I use Apollo Client to handle graphQL requests in my applications, so I'll show you how I would store those fragments in separate files and import them into the main query using that approach.
Here is how my iconColumnFields fragment would look stored in its own file.
You'll notice it looks a little different. Mainly, you should see that we are exporting the fragment within the apollo client gql function. We can now import this into our main query. This too will look a little different.
The imports add a few extra lines of code above the query, but the query itself is very easy to read and understand.
Whether you have used fragments before or not, I hope you can see the benefit in using them for resuable chunks of your query and also for breaking large queries into smaller more mantainable sections.
I hope you found this helpful, if you did, let me know on twitter.