⬡ GraphQL Beginner

What are fragments in GraphQL?

Answer

Fragments are reusable units of fields that can be shared across multiple queries. They help avoid repeating the same set of fields. Define a fragment with fragment UserFields on User { id name email avatar } and use it with the spread operator: { user(id: "1") { ...UserFields } }. Fragments must specify the type they apply to (on User) to ensure type safety. They are especially useful in front-end codebases (with tools like Apollo Client) where multiple components need the same fields from a shared type, promoting colocation of data requirements with UI components.