Fragments for Reusable Selections
You'll learn how to define reusable field selections in GraphQL to avoid repeating yourself and make queries easier to maintain.
What Are Fragments?
A fragment is a reusable unit of fields that you can include in multiple queries. Think of it like a template or blueprint for a set of fields you commonly request together. Instead of writing the same 10 fields every time you need user information, you define those fields once in a fragment and reference it wherever needed.
Fragments help you follow the DRY principle (Don't Repeat Yourself) when working with GraphQL queries.
Defining and Using Fragments
A fragment has a name and specifies which type it applies to. Here's how you define one:
fragment UserDetails on User {
id
name
email
profilePicture
}
Now you can use this fragment in any query that returns a User type:
query GetUserAndFriends {
currentUser {
...UserDetails
}
friends {
...UserDetails
}
}
The ... syntax is called the spread operator—it "spreads" the fragment's fields into that location.
Why Fragments Matter
Without fragments, you'd duplicate the same field list multiple times. If you later need to add phoneNumber to every user query, you'd have to update dozens of places. With a fragment, you update one definition, and all queries using it automatically include the new field.
Fragments also make complex queries more readable by giving meaningful names to field groups.
Key Takeaway: Fragments let you define reusable field selections once and spread them across multiple queries, keeping your GraphQL code clean, maintainable, and DRY.