GraphQL Fragments: Let Each Component Own Its Data
GraphQL queries look clean at first. One request gets all your data. Then your app grows.
Your page query starts collecting fields for many different child components. You add a field for a new component. Six weeks later you delete that component. You forget to remove the field from the main query. Now no one knows if it is safe to delete. The query grows forever.
Fragments fix this. Most teams use them as a way to copy and paste fields. This is the wrong way. Fragments should be a model for component ownership.
A fragment is a named group of fields for a specific type.
Example: fragment UserBadge on User { id name avatarUrl }
You spread this fragment into any query that needs a User.
The real value comes from where you save the fragment. Do not put them in a shared file. Put the fragment in the same file as the component that uses it.
This is called co-location. Each component declares its own data needs.
When a component needs a new field, you add it to its fragment. The parent query updates automatically. When you delete a component, you delete its fragment. The query shrinks. The parent component does not need to know about the internal fields of its children.
Data masking makes this even better. With masking enabled, a component only sees the fields it asked for in its own fragment. Even if the server sends extra data, your component cannot access it.
This creates a strict contract.
- TypeScript knows exactly what data each component has.
- If you remove a field from a fragment, TypeScript shows you every error.
- Refactoring becomes a simple type-check instead of a search through your whole codebase.
Use fragments when:
- Multiple components use the same type like User or Product.
- Your page queries are too long.
- You accidentally leave dead fields in your queries.
- You want TypeScript safety for your data.
Start small. Find one component that gets data from a parent query. Move its fields into a fragment. Put that fragment in the component file.
Fragments ensure your data fetching matches your UI as your app grows.
Source: https://dev.to/grimicorn/graphql-fragments-let-each-component-own-its-data-5359
