You are designing a GraphQL API. What are "fragments"? Please what is a GraphQL fragment, what problem do they solve? (Reusing parts of a query), and provide an example of defining and using a fragment in a query.
Assistant
We are designing a GraphQL API. The user asks about GraphQL fragments.
We need to explain:
What is a GraphQL fragment?
What problem do they solve? (Reusing parts of a query)
Provide an example of defining and using a fragment in a query.
Let's structure the answer accordingly.
GraphQL Fragments
What is a GraphQL Fragment?
A GraphQL fragment is a reusable piece of a query that defines a set of fields on a specific GraphQL type. It allows you to organize complex queries by breaking them down into smaller, reusable units, especially when the same selection set (fields) is needed in multiple places.
Fragments are defined with the fragment keyword followed by:
Fragment name (custom identifier)
Type condition (on TypeName) specifying which GraphQL object type the fragment applies to
Field selection set (the fields to include)
What Problem Do Fragments Solve?
Fragments primarily solve query reuse and maintainability issues:
Problem Without Fragments
Solution With Fragments
❌ Duplicate field selections across multiple queries
✅ Define once, reuse everywhere
❌ Hard to update when field requirements change
✅ Update fragment, all queries automatically reflect changes
❌ Complex queries become unwieldy and repetitive
✅ Break queries into logical components
❌ Violates DRY (Don't Repeat Yourself) principle
✅ Enforces DRY for field selections
Key use cases:
Reusing common fields across components in frontend applications
Sharing field sets between multiple queries/mutations in a single operation
Organizing large queries for better readability
Handling interface/union types with type-specific fields
Example: Defining and Using Fragments
1. Schema Setup (Context)
Assume a simple schema with a User type:
graphql
type User {
id: ID!
name: String!
email: String!
profilePicture: URL
friends: [User!]!
}
2. Defining a Fragment
graphql
# Define a fragment for basic user information
fragment UserBasicInfo on User {
id
name
email
profilePicture
}
Explanation:
UserBasicInfo: Fragment name (must be unique within operation)
on User: Type condition (must match the object type the fragment will be used on)
Inside {}: Selection set for the User type
3. Using Fragments in a Query
graphql
# Query using the fragment in multiple places
query GetUserAndFriends {
user(id: "123") {
...UserBasicInfo # Spread fragment here
friends {
...UserBasicInfo # Reuse same fragment for friends
friends { # Nested usage
...UserBasicInfo
}
}
}
}
Resulting field set:
The query effectively becomes:
graphql
query GetUserAndFriends {
user(id: "123") {
id
name
email
profilePicture
friends {
id
name
email
profilePicture
friends {
id
name
email
profilePicture
}
}
}
}
4. Multiple Fragments in One Query
graphql
fragment UserBasicInfo on User {
id
name
}
fragment UserContactInfo on User {
email
profilePicture
}
query GetUserDashboard {
currentUser {
...UserBasicInfo
...UserContactInfo
}
recentlyActiveUsers {
...UserBasicInfo
...UserContactInfo
}
}
5. Fragments with Type Conditions (Interfaces/Unions)
For abstract types:
graphql
fragment ProfileFields on User {
id
name
bio
}
fragment AdminFields on Admin {
id
name
permissions
}
query SearchPeople($type: PersonType!) {
people(type: $type) {
__typename
... on User {
...ProfileFields
}
... on Admin {
...AdminFields
}
}
}
Key Rules & Best Practices
Fragment naming: Use descriptive names (e.g., UserListItem, PostSummary)
Type conditions: Must match the parent field's return type
Fragment spreading: Use ...FragmentName within selection sets
No cyclic dependencies: Fragments cannot reference themselves directly/indirectly
Tooling support: Most GraphQL clients (Apollo, Relay) encourage fragment-first patterns
Real-World Frontend Example (React + Apollo)
javascript
// Define fragment alongside component
const USER_BASIC_INFO = gql`
fragment UserBasicInfo on User {
id
name
avatarUrl
}
`;
// Use in component query
const GET_USER = gql`
query GetUser($id: ID!) {
user(id: $id) {
...UserBasicInfo # Reuse fragment
}
}
${USER_BASIC_INFO} # Include fragment definition
`;
// Reuse in another component
const GET_FRIENDS = gql`
query GetFriends {
friends {
...UserBasicInfo # Same fragment, different context
}
}
${USER_BASIC_INFO}
`;
Fragments fundamentally enable:
✅ Component-driven development: Each component declares its data needs via fragments
✅ Co-location: Fragments live with components that use them
✅ Automatic updates: When component requirements change, update fragment → all queries update
✅ Performance: Enables persisted queries and automatic field tracking
By using fragments, you create a modular, maintainable, and scalable GraphQL API consumption pattern that aligns with modern component-based architectures.