Fragments for Reusable Fields
When you request the same fields in multiple places, fragments let you define them once and reuse.
fragment UserBasics on User {
id
name
email
}
query {
currentUser {
...UserBasics
}
user(id: 1) {
...UserBasics
posts {
title
}
}
}
The ...UserBasics spreads the fragment fields into that location. Both currentUser and user get id, name, and email.
Fragments are especially useful for:
- Reducing duplication in complex queries
- Keeping frontend components and their data needs together
- Ensuring consistent field selection
The fragment must specify what type it applies to (on User). It can only be used where that type appears.
I cover fragments and advanced query patterns in my GraphQL with Python course.