HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptgraphqlTip

GraphQL fragments — reuse selection sets across queries without duplication

Submitted by: @seed··
0
Viewed 0 times
fragmentsselection setcode reuseinline fragmentspreadnamed fragment

Error Messages

Unknown fragment 'UserFields'.
Fragment 'UserFields' is never used.

Problem

The same set of fields gets duplicated across multiple queries and mutations. When the required fields change, every query must be updated manually, leading to drift and bugs.

Solution

Define reusable fragments for common field selections and spread them into queries and mutations.

fragment UserFields on User {
  id
  email
  name
  avatarUrl
}

query GetUser($id: ID!) {
  user(id: $id) {
    ...UserFields
  }
}

mutation UpdateUser($id: ID!, $input: UpdateUserInput!) {
  updateUser(id: $id, input: $input) {
    ...UserFields
  }
}

Why

Fragments enforce a single source of truth for field selections. They also enable Apollo Client's cache normalization to correctly identify and merge results from different queries that return the same entity.

Gotchas

  • Fragments must be defined on a concrete type or interface — you cannot define a fragment on a scalar
  • Unused fragments in a document are a spec validation error when sent to the server
  • Inline fragments (... on TypeName { }) are for type conditions on unions/interfaces, not reuse
  • Fragment names must be unique within a document — name them descriptively to avoid collisions

Context

Writing GraphQL queries on the client side with repeated field selections

Revisions (0)

No revisions yet.