0
0
GraphQLquery~3 mins

Why Fragments for reusable selections in GraphQL? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could fix all your repeated query fields by changing just one piece of code?

The Scenario

Imagine you are building a website that shows user profiles on many pages. Each page needs the same user details like name, email, and profile picture. You copy and paste the same list of fields everywhere in your GraphQL queries.

The Problem

Copying the same fields again and again is slow and boring. If you want to add or change a field, you must update every query manually. This causes mistakes and wastes time.

The Solution

Fragments let you write the list of fields once and reuse it in many queries. This keeps your code clean and easy to update. Change the fragment once, and all queries using it get updated automatically.

Before vs After
Before
query GetUser { user { id name email picture } } query GetFriend { friend { id name email picture } }
After
fragment UserDetails on User { id name email picture } query GetUser { user { ...UserDetails } } query GetFriend { friend { ...UserDetails } }
What It Enables

Fragments make your GraphQL queries simpler, reusable, and easier to maintain across your whole app.

Real Life Example

A social media app shows user info on profile pages, friend lists, and comments. Using fragments, it fetches user details consistently everywhere without repeating code.

Key Takeaways

Writing repeated fields manually is slow and error-prone.

Fragments let you define reusable field sets once.

Updating fragments updates all queries using them automatically.