Log in to GraphQL Editor
GraphQL Fragments and the benefits of using them
Tomek

Tomek Poniatowicz

4/29/2019

GraphQL Fragments and the benefits of using them

In this short read, I will try to break down for you the concept of GraphQL fragments. What are the fragments in GraphQL and how you can benefit from using them?

GraphQL Fragments

In GraphQL you sometimes need to query for the same fields in multiple queries. This requires defining these fields over again which can lead to tiny, but very annoying errors.

David Walsh Twitter

That's why GraphQL includes reusable units called fragments. Fragments let you construct reusable pieces of query logic (an equivalent to UI component of a design system). The small part of a query makes, ready to be used where needed, makes our work is way more effective, and possibly lower odds of making a simple typo.

Let's say we have a user type containing some standard fields like:

user

We can use the fragment to represent a set of specific fields i.e. online contact details:

details so when querying for online details we can referer to the fragment instead of querying for all fields separately:

getUsers

Less typing, cleaner code, easier life :)

The benefits of using fragments

GraphQL fragments allow you to reuse parts of your queries and provide such qualities as:

  • consistency - higher confidence that you’re always working on the right fields i.e when running mutations you know you update the right data.
  • better code organization - fragments improve the structure & reusability of GraphQL code, which is very handy in terms of team collaboration
  • improved communication with GraphQL server - querying for fragments isolates a component from any unwanted data.

Sounds good right? So if you are wondering if its worth using GraphQL fragments the answers is simple - YES!

Check out our other blogposts

Tina Cloud -  a headless CMS backed by Git
Michał Tyszkiewicz
Michał Tyszkiewicz
Tina Cloud - a headless CMS backed by Git
4 min read
almost 3 years ago
Postman now supports GraphQL!
Tomek Poniatowicz
Tomek Poniatowicz
Postman now supports GraphQL!
1 min read
almost 5 years ago
Searchkit - Search UI with GraphQL, React and Elasticsearch
Tomek Poniatowicz
Tomek Poniatowicz
Searchkit - Search UI with GraphQL, React and Elasticsearch
3 min read
over 3 years ago

Ready for take-off?

Elevate your work with our editor that combines world-class visual graph, documentation and API console

Get Started with GraphQL Editor