Back to results for “GraphQL”
Node.js › GraphQL

What is the purpose of GraphQL fragments, and how do they help avoid duplicating field selections across multiple queries?

Intermediate

Answer

A fragment defines a reusable, named set of fields on a specific type, which can then be included (spread) into multiple different queries or mutations wherever that same set of fields is needed -- this avoids repeating an identical, potentially large list of fields across every query that needs the same shape of data, and makes it easier to keep field selections consistent when the same data shape (like a summary view of a User) is used in several different places throughout an application.
fragment UserSummary on User {
  id
  name
  avatarUrl
}

query GetPost {
  post(id: "1") { title, author { ...UserSummary } }
}

query GetComment {
  comment(id: "1") { text, author { ...UserSummary } }
}
Real-world example A frontend application defines a UserSummary fragment once and reuses it across a dozen different queries that all need to display the same basic author information, ensuring that if the summary fields ever need to change, only the single fragment definition needs updating rather than every individual query.

Common follow-ups: How do GraphQL fragments relate to and support component-based frontend architectures, like colocating a fragment with a specific React component?;What's the difference between a named fragment and an inline fragment (used for querying fields specific to one type in a union or interface)?