⬡ GraphQL
Beginner
What are GraphQL fragments?
Answer
Fragments are reusable units of fields that can be included in multiple operations, reducing duplication. Define a fragment: fragment UserFields on User { id name email avatar }. Use with spread operator ...: query { user(id: "1") { ...UserFields posts { title } } }. Benefits: (1) DRY principle — define shared field sets once. (2) Co-location: UI components (in React + Apollo) can declare their own data fragments and compose them. (3) Inline fragments: used for type conditions in unions/interfaces: { search { ... on User { name } ... on Post { title } } }. Fragments must be used on a specific type (on TypeName). Named fragments are sent to the server; the server merges them into the operation before execution.