Organizing GraphQL files with components using near-operation-file pattern
Now that you know how to write GraphQL operations, let's discuss where to organize them. Colocation keeps your GraphQL files next to the components that use them, improving discoverability and maintainability.
In our GraphQL setup, "colocation" refers to the near-operation-file preset pattern where:
.graphql files are placed in the same folder as the components that use them.graphql.ts) are created alongside the .graphql filesThis approach, documented in the Guild's near-operation-file guide, provides the best balance of organization and type safety.
For operations specific to a single component:
Old Pattern: All operations in a central location
Problems:
New Pattern: Operations next to components
Benefits:
When codegen runs (automatically during turbo run dev or manually with turbo run codegen), the near-operation-file preset:
.graphql files in your app.graphql.ts file next to each oneFor this operation:
Generates this TypeScript file:
For components with multiple operations:
.graphql files in the same folder as components.graphql.ts filesThere are two different ways a fragment can appear in multiple places, and only one is an anti-pattern:
ChatroomChatbotsData) is spread via ...ChatroomChatbotsData into a parent fragment (LiveChatroomData). The parent query fetches all data in one request, and typed props flow downward to each child component. This is the recommended approach for decomposing large fragments: it does not violate the "don't share fragments" guideline.useQuery call using that fragment's fields. This creates duplicate queries and breaks the single-query-at-the-top pattern.If a fragment is genuinely needed in multiple unrelated contexts, consider whether a shared parent component should own the query, or whether the relevant components can be restructured so data flows downward via props.
Next, we'll learn about fragments, which help optimize and reuse field selections across your operations.
On this page