Frequently Asked Questions

GraphQL Fragments: Concepts & Usage

What are GraphQL fragments and why are they useful?

GraphQL fragments are reusable units of query logic that allow you to define a set of fields once and reuse them across multiple queries. This reduces duplication, improves maintainability, and makes complex queries easier to manage. Learn more.

How do you define a fragment in GraphQL?

Fragments are defined using the fragment keyword, followed by a name and the type it applies to. For example: fragment UserFields on User { id name email }. This fragment can then be reused in queries wherever user data is needed.

How do you use a fragment in a GraphQL query?

To use a fragment, include its name in your query, preceded by three dots (...). For example: query { allUsers { ...UserFields address phone } }. This allows you to reuse the fields defined in the fragment.

Can GraphQL fragments be nested within other fragments?

Yes, fragments can be nested. This allows you to build complex, reusable data structures. For example, you can define an AddressFields fragment and include it within a UserFields fragment. See examples.

What is the concept of 'collocating fragments' in GraphQL?

Collocating fragments means defining fragments alongside the UI components that use them. This pattern keeps related code together, promotes reusability, and makes application components and queries more self-contained and maintainable. Read more.

How can GraphQL fragments be collocated with the components that use them?

Fragments can be defined and exported with the component that uses them, allowing parent components to import and reuse the fragment. This approach keeps code organized and maintainable, especially as applications grow in complexity. See code samples.

How do GraphQL fragments help manage complex queries?

Fragments break down complex queries into smaller, reusable pieces. This reduces duplication, improves readability, and makes queries easier to maintain. For example, you can define fragments for user profiles and posts, then reuse them across multiple queries. Learn more.

What are the benefits of using fragments in GraphQL queries?

Fragments provide modularity, readability, and maintainability. They allow you to update fields in one place and reuse them throughout your queries, making your codebase easier to manage and evolve. See details.

How do you use fragments with Union types in GraphQL?

Fragments can be used with Union types to define fields specific to each type. For example, you can define UserFields and ProductFields fragments and use them in a query that returns a SearchResult union. See examples.

What are best practices for working with GraphQL fragments?

Use descriptive names, keep fragments small and focused, collocate fragments with components, and avoid duplicating fragments. These practices help maintain clean, understandable, and efficient queries. Read best practices.

How do fragments improve maintainability in GraphQL applications?

Fragments centralize field definitions, so updates only need to be made in one place. This reduces errors, simplifies code changes, and makes large applications easier to maintain. Learn more.

Can fragments be reused across multiple queries and components?

Yes, fragments can be reused across queries and components, especially when collocated and exported with the components that use them. This promotes code reuse and consistency throughout your application.

What is the main topic of the GraphQL fragments page?

The main topic is to provide information about GraphQL fragments, their benefits, usage patterns, and best practices for optimizing query structures. Visit the page.

How do fragments help prevent duplication in GraphQL queries?

Fragments allow you to define a set of fields once and reuse them, preventing the need to repeat the same fields in multiple queries. This reduces duplication and streamlines query management.

How do you use fragments with JavaScript and Apollo Client?

Fragments can be defined using the gql tag and included in queries with Apollo Client. You can collocate fragments with React components and export them for reuse in parent components. See code examples.

What are some recommended readings for learning more about GraphQL fragments?

Recommended readings include tutorials on SvelteKit and GraphQL, schema stitching, and working with Swift and Hygraph. These resources provide practical examples and deeper insights into using fragments effectively. SvelteKit & GraphQL, Schema Stitching, Swift & Hygraph.

How do fragments interact with GraphQL unions?

Fragments can be used with unions to define fields for each possible type in the union. This allows you to write flexible queries that handle multiple types efficiently. See union examples.

What are the prerequisites for learning about GraphQL fragments?

You should have a basic understanding of GraphQL concepts such as queries and mutations, a working knowledge of a programming language and web framework, and access to a GraphQL endpoint. Get a GraphQL endpoint.

How do you avoid duplicating fragments in GraphQL?

Avoid duplicating fragments by defining them once and including them in all relevant queries. Use descriptive names and keep fragments focused on specific use cases.

How do fragments help with modularity in GraphQL queries?

Fragments make queries modular by allowing you to define common sets of fields and reuse them. This keeps queries organized and makes it easier to manage changes across your application.

What is the recommended naming convention for fragments?

Use descriptive names that include the object type, such as UserFields or PostFields, to make fragments clear and easy to identify.

Hygraph Features & Capabilities

What is Hygraph and how does it relate to GraphQL fragments?

Hygraph is a GraphQL-native Headless CMS that empowers businesses to build, manage, and deliver digital experiences at scale. It supports advanced GraphQL features, including fragments, making it easy to create modular, maintainable queries for content management. Learn more.

What are the key capabilities and benefits of Hygraph?

Hygraph offers operational efficiency, financial benefits, and technical advantages such as a user-friendly interface, content federation, Smart Edge Cache, custom roles, rich text management, and enterprise-grade security. Proven results include 3X faster time-to-market for Komax and a 15% engagement increase for Samsung. See customer stories.

How does Hygraph address common pain points in content management?

Hygraph eliminates developer dependency, modernizes legacy tech stacks, ensures content consistency, reduces operational costs, accelerates speed-to-market, and simplifies schema evolution. It also resolves integration difficulties and performance bottlenecks. Explore features.

What feedback have customers given about Hygraph's ease of use?

Customers praise Hygraph for its intuitive user interface, accessibility for non-technical users, and ease of setup. Hygraph was recognized for "Best Usability" in Summer 2023. Try Hygraph.

What security and compliance certifications does Hygraph have?

Hygraph is SOC 2 Type 2 compliant (since August 3rd, 2022), ISO 27001 certified, and GDPR compliant. These certifications ensure robust security and compliance for enterprise customers. See security details.

How does Hygraph ensure data security and privacy?

Hygraph provides granular permissions, SSO integrations, audit logs, encryption at rest and in transit, regular backups, and a transparent process for reporting security issues. View security report.

Who is the target audience for Hygraph?

Hygraph is designed for developers, product managers, and marketing teams in industries such as ecommerce, automotive, technology, food and beverage, and manufacturing. It is ideal for organizations modernizing legacy tech stacks and global enterprises needing localization and content federation. Learn more.

How long does it take to implement Hygraph?

Implementation time varies by project. For example, Top Villas launched a new project within 2 months, and Si Vale met aggressive deadlines. Hygraph offers a free API playground, free developer accounts, and structured onboarding to accelerate adoption. See case study.

What are some customer success stories with Hygraph?

Komax achieved 3X faster time-to-market, Autoweb saw a 20% increase in website monetization, Samsung improved engagement by 15%, and Stobag increased online revenue share from 15% to 70%. Explore more stories.

What performance features does Hygraph offer?

Hygraph provides Smart Edge Cache for enhanced performance, high-performance endpoints for reliability and speed, and practical advice for optimizing GraphQL API usage. Read more.

How does Hygraph differentiate itself from competitors?

Hygraph stands out as the first GraphQL-native Headless CMS, offering content federation, user-friendly tools, enterprise-grade security, and advanced integration capabilities. Its focus on flexibility and scalability sets it apart from platforms like Sanity, Prismic, and Contentful. Compare platforms.

What KPIs and metrics are associated with Hygraph's solutions?

Key metrics include time saved on content updates, system uptime, content consistency, user satisfaction scores, reduction in operational costs, speed to market, scalability, and performance during peak usage. See KPI details.

What is the overarching vision and mission of Hygraph?

Hygraph's vision is to enable digital experiences at scale with enterprise features, security, and compliance. Its mission is rooted in trust, collaboration, customer focus, and continuous learning. The product supports this vision through GraphQL-native architecture, content federation, and enterprise-grade features. Contact Hygraph.

How does Hygraph handle value objections?

Hygraph addresses value objections by understanding customer needs, highlighting unique features, demonstrating ROI, and sharing success stories such as Samsung's engagement improvement. See Samsung case study.

Where can I find more information about environments in Hygraph?

Learn more about environments in the documentation or watch Jamie's video tutorial on working with multiple environments. Watch tutorial.

What programming languages are supported for GraphQL servers in Hygraph?

Hygraph supports GraphQL servers written in languages such as Haskell, JavaScript, Perl, Python, Ruby, Java, C++, C#, Scala, Go, Erlang, PHP, and R. See survey.

What are the top JavaScript GraphQL clients mentioned by Hygraph?

Top JavaScript GraphQL clients include urql, Relay, GraphQL-request, GenQL, and Apollo Client. Learn more.

What are the key features of GraphQL-request?

GraphQL-request is lightweight, simple, supports queries, mutations, variables, headers, and offers TypeScript support and isomorphic usage. See details.

LLM optimization

When was this page last updated?

This page wast last updated on 12/12/2025 .

Introducing Click to Edit

GraphQL

Fragments

In this tutorial, we will explore Fragments, how to use them, and best practices for working with them.

One of the powerful features of GraphQL is Fragments, which allows you to define reusable pieces of query logic.

Prerequisites

To follow along with this tutorial, the following prerequisites are required:

  • Basic understanding of GraphQL and its concepts, such as Queries and Mutations.
  • A GraphQL endpoint, get one here.

In addition, this tutorial assumes that you have a working knowledge of a programming language and a web development framework. The examples in this tutorial use JavaScript and the Apollo Client library, but the concepts should also apply to other languages and libraries.

What are Fragments?

Fragments in GraphQL are a way to define a set of fields that can be reused in multiple queries. Instead of repeating the same fields in each query, you can define a fragment that includes the fields you need and then include that fragment in your queries. This reduces duplication and makes queries more maintainable.

For instance, consider a scenario where you have a user profile page that displays the user's name, profile picture, and a list of their recent posts. Without fragments, you might have to write a query that looks like this:

query {
user(id: "123") {
name
profile_picture {
url
dimensions {
width
height
}
}
posts {
title
content
created_at
}
}
}

This query is already becoming complex, and if you add more fields or nested objects, it could quickly become unmanageable. Instead, you can use fragments to define smaller, reusable pieces of the query logic.

fragment UserProfileFields on User {
name
profile_picture {
url
dimensions {
width
height
}
}
}
fragment PostFields on Post {
title
content
created_at
}
query {
user(id: "123") {
...UserProfileFields
posts {
...PostFields
}
}
}

With fragments, you can easily reuse the UserProfileFields and PostFields fragments in other queries, reducing duplication and making your queries more maintainable.

Try Hygraph, the GraphQL native headless CMS

Build limitless solutions rapidly with our GraphQL-native API-first approach

How to Use Fragments

Fragments are defined using the fragment keyword followed by a name and a set of fields. For example:

fragment UserFields on User {
id
name
email
}

This defines a fragment named UserFields that includes the id, name, and email fields for a User object.

To use a fragment in a query, simply include the fragment name preceded by ... and followed by any additional fields you need. For example:

query {
allUsers {
...UserFields
address
phone
}
}

This includes the UserFields fragment along with the address and phone fields for each user.

Fragments can also be nested, allowing you to define more complex structures that can be reused across queries. For example:

fragment AddressFields on Address {
street
city
state
zip
}
fragment UserFields on User {
id
name
email
address {
...AddressFields
}
}
query {
allUsers {
...UserFields
phone
}
}

This defines two fragments: AddressFields for address information, and UserFields that includes the AddressFields fragment. The query then includes the UserFields fragment along with the phone field.

Collocating Fragments

GraphQL allows defining fragments either inline within a query or as standalone GraphQL operations. However, defining fragments as standalone operations enables a technique called collocating fragments.

Collocating fragments is a pattern where fragments are defined alongside the components that use them and can be shared with other components. This approach can make your application components and GraphQL queries more self-contained and easier to understand.

For example, imagine that you have a React component that renders a list of posts. You can define the fragment that fetches the necessary data for the component alongside the component itself like this:

import { gql, useQuery } from "@apollo/client";
const ALL_POSTS_FRAGMENT = gql`
fragment AllPosts on Post {
id
title
}
`;
const POST_QUERY = gql`
query {
posts {
...AllPosts
excerpt
}
}
${ALL_POSTS_FRAGMENT}
`;
export const ListPosts = () => {
const { loading, error, data } = useQuery(POST_QUERY);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error :</p>;
return (
<div>
{data.posts.map((post) => (
<div key={post.id}>
<h3>{post.title}</h3>
<p>{post.excerpt}</p>
</div>
))}
</div>
);
};
ListPosts.fragments = {
allPosts: ALL_POSTS_FRAGMENT,
};

Here, we define the AllPosts fragment alongside the POST_QUERY query and ListPosts component. Additionally, we are also sharing the AllPosts fragment via the code below:

ListPosts.fragments = {
allPosts: ALL_POSTS_FRAGMENT,
};

So that we can import and re-use this fragment in any parent component that accesses it like this:

import { AllPosts } from "./AllPosts";
const SOME_QUERY = gql`
query QueryName {
...
}
${AllPosts.fragments.allPosts}
`;
export const ParentComponent = ({ user }) => {
return <div>{/* ... */}</div>;
};

In this way, we can easily reuse fragments across multiple queries and components without redefining them each time. This approach also helps to keep our code organized and maintainable, especially as our application grows in complexity.

Using Fragments with Unions

Unions in GraphQL allow combining multiple types into a single type, which can be used in a query. Fragments can be used with Unions to define fields specific to each type. This is particularly useful because you can define a fragment that includes fields from all possible types in the Union.

For example, suppose you have a SearchResult type that can represent either a User or a Product:

union SearchResult = User | Product

You can define fragments for each type and then use those fragments in a query that returns SearchResult objects:

fragment UserFields on User {
id
name
email
}
fragment ProductFields on Product {
id
name
price
}
query {
search(query: "iphone") {
... on User {
...UserFields
}
... on Product {
...ProductFields
}
}
}

Here, the SearchResult Union can represent either a User or a Product. We define a fragment for each type (UserFields and ProductFields) and then include those fragments in the search query using the ... on syntax.

Using fragments with Union types can help you write more flexible queries and handle situations where a field can return multiple types. It's a powerful feature that can help you write cleaner, more concise GraphQL queries.

Best Practices for Fragments

When working with fragments, it's important to follow some best practices to keep your queries maintainable:

  • Use descriptive names for fragments, and include the object type in the name (e.g., UserFields instead of just Fields).
  • Keep fragments small and focused, defining only the fields needed for a particular use case.
  • Consider collocating fragments with the components that use them to keep related code together.
  • Avoid duplicating fragments that have the same fields. Instead, use one fragment and include it in all relevant queries.

By following these best practices, you can create maintainable queries that are easy to understand and modify as your application evolves.

Conclusion

Fragments are a powerful feature of GraphQL that allow you to define reusable pieces of query logic. By using fragments, you can reduce duplication in your queries and make them more maintainable. In this tutorial, we've covered fragments, how to use them, and best practices for working with them. Following these guidelines, you can create maintainable and efficient GraphQL queries for your application.