Create Reusable Query Units and Fields Using Fragments

Learn about the GraphQL fragments used to prevent duplication of GraphQL queries.

Let’s say our customer base has grown, and our new clients require more information. For example, the clients want to compare pizzas side-by-side while also looking at the available toppings. This operation would need us to repeat the fields at least once for each comparison.

GraphQL fragments

GraphQL fragments allow us to build sets of fields and then use them in queries as needed.

How to convert repetitive GraphQL queries

Before we start working with GraphQL fragments, we need to do the following:

  • Find the repeated fields that are used in multiple places.

  • Declare all the fields that are used as fragments.

  • Replace earlier fields with one of the fragments that we defined and use spread syntax.

Now, we’ll be able to refactor the previous query. We’ve reproduced it below:

Get hands-on with 1200+ tech skills courses.