Skip to content
GraphQL

Fragments

Reusable selection sets.

By EZ4Code Team
fragmentreuse

Code

fragment BookSummary on Book {
  id
  title
  author {
    name
  }
}

query GetBooks {
  books {
    ...BookSummary
  }
}

query GetBook($id: ID!) {
  book(id: $id) {
    ...BookSummary
    pages
  }
}

Explanation

Fragments are named, reusable selection sets declared with a target type, then spread into queries with the ... syntax. They keep large queries DRY and let client libraries co-locate component data requirements. Colocated fragments are the foundation of tools like Relay and Apollo's store normalization.

More GraphQL Snippets