0
0
GraphqlConceptBeginner · 3 min read

What is Fragment in GraphQL: Explanation and Example

In GraphQL, a fragment is a reusable piece of query logic that lets you group fields you want to fetch together. It helps avoid repeating the same fields in multiple queries or parts of a query by defining them once and including them wherever needed.
⚙️

How It Works

Think of a fragment in GraphQL like a reusable recipe card for fetching data. Instead of writing the same list of fields over and over in different queries, you write the list once as a fragment. Then, you can include that fragment wherever you want in your queries.

This saves time and keeps your queries clean and easy to read. It also helps when you want to update the fields you fetch — you only change the fragment, and all queries using it get updated automatically.

💻

Example

This example shows a fragment named UserDetails that fetches a user's id and name. The fragment is then used in two different queries to avoid repeating the same fields.

graphql
fragment UserDetails on User {
  id
  name
}

query GetUser1 {
  user(id: "1") {
    ...UserDetails
    email
  }
}

query GetUser2 {
  user(id: "2") {
    ...UserDetails
    age
  }
}
Output
{ "data": { "user": { "id": "1", "name": "Alice", "email": "alice@example.com" } } }
🎯

When to Use

Use fragments when you have fields that you need to fetch repeatedly in different queries or parts of a query. This is common in apps where you show the same user information in many places, like profiles, comments, or lists.

Fragments help keep your queries DRY (Don't Repeat Yourself), making them easier to maintain and less error-prone. They are especially useful in large projects with complex data needs.

Key Points

  • Fragments group fields to reuse in multiple queries.
  • They reduce repetition and simplify query updates.
  • Fragments improve query readability and maintenance.
  • Use them when the same data fields appear in many places.

Key Takeaways

Fragments let you reuse sets of fields in GraphQL queries to avoid repetition.
They make queries cleaner and easier to maintain by centralizing common fields.
Use fragments when the same data fields are needed in multiple queries or parts of a query.
Updating a fragment updates all queries that use it, saving time and reducing errors.