GraphQL fragments explained
Tags: graphql, javascript, webdev
Published: 2019-10-10 21:06:42

---
title: GraphQL fragments explained
published: true
tags: graphql, javascript, webdev
canonical_url: https://blog.logrocket.com/graphql-fragments-explained/
cover_image: https://thepracticaldev.s3.amazonaws.com/i/8hkm5j0tralrufrvgzcq.png
---
**Written by [Adhithi Ravichandran](https://blog.logrocket.com/author/adhithiravichandran/)**✏️

## What is a GraphQL fragment?

In this post, we are going to learn about what a **fragment** is in GraphQL. A [GraphQL fragment](https://graphql.org/learn/queries/#fragments) is a reusable part of the query. In GraphQL, you may run into situations where you need to query for the same fields in different queries. If you notice that your query has many repetitive fields in multiple areas, you can consolidate them into a reusable unit called a fragment.

A GraphQL fragment lets you build multiple fields, and include them in multiple queries. You can think of it as functions in programming languages, that are reusable units.

_A GraphQL Fragment is a reusable unit of a GraphQL query, which creates a shared piece of query logic._

## The components of a GraphQL fragment

Let’s take a look at the different parts of a GraphQL fragment with a sample structure below:

```jsx
fragment Name on TypeName {
  field1
  field2
  field3
}
```

A fragment consists of three unique components:

- **Name** : This is the unique name of the fragment (each fragment can have its own name)
- **TypeName** : The type of object the fragment is going to be used on. This indicates which nested object, from the GraphQL schema, this fragment is created on
- **Body** : The last part is the body of the fragment. The body of the fragment defines the fields that will be queried for

## Benefits of using a GraphQL fragment

So why are fragments cool within a GrapQL query?

- **Reusability** – With fragments, you can organize your queries into reusable units
- **Caching** – [GraphQL clients](https://www.apollographql.com/docs/react/caching/cache-interaction/) make use of fragments, to provide caching options

[![LogRocket Free Trial Banner](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/f760c-1gpjapknnuyhu8esa3z0jga.png?resize=1200%2C280&ssl=1)](https://logrocket.com/signup/)

## Creating GraphQL fragments

Let’s learn how to create GraphQL fragments with some examples. For the examples in this blog post, I am using [GitHub’s public API](https://developer.github.com/v4/) and writing queries against it. You can follow along by signing into your GitHub account, and executing the queries from the [GitHub GraphQL Explorer](https://developer.github.com/v4/explorer/).

Notice that we are querying for the same fields inside the **owner** field multiple times. This is a good place to create a fragment:

```jsx
{
  googleRepo: repository (owner:"google", name:"WebFundamentals") {
    name
    owner {
      id,
      avatarUrl
      resourcePath
      url
    }
  }
  facebookRepo: repository (owner:"facebook", name:"react") {
    name
    owner {
      id,
      avatarUrl
      resourcePath
      url
    }
  }
}
```

We can rewrite our query to use a fragment. Fragments are created with the keyword fragment.

We can create a fragment called `ownerInfo`. While creating fragments we have to let GraphQL know on which field it is created. In our case, we are creating the fragment on the `RepositoryOwner` field. Within our fragment definition, we can include all the fields that we are querying for on the `RepositoryOwner` object. We are adding `id`, `avatarUrl`, `resourcePath` and `url` as fields to our fragment.

```jsx
// fragment ownerInfo for RepositoryOwner fields
fragment ownerInfo on RepositoryOwner {
  id
  avatarUrl
  resourcePath
  url
}
```

## Using a GraphQL fragment

You can then use the fragment that we created in the previous example, within the query by using the … operator and providing the fragment’s name as shown below:

```jsx
// GraphQL Query with fragments

{
  googleRepo: repository(owner: "google", name: "WebFundamentals") {
    name
    owner {
      ...ownerInfo //fragment
    }
  }
  facebookRepo: repository(owner: "facebook", name: "react") {
    name
    owner {
     ...ownerInfo //fragment
    }
  }
}
```

The snippet shown below is the JSON response after using a fragment. Notice, that there won’t be any changes to the response returned with the use of fragments. Fragments simply make your query clean, readable and reusable. It has no effect on the query response that comes back.

```jsx
// GraphQL JSON Response

{
  "data": {
    "googleRepo": {
      "name": "WebFundamentals",
      "owner": {
        "id": "MDEyOk9yZ2FuaXphdGlvbjEzNDIwMDQ=",
        "avatarUrl": "https://avatars1.githubusercontent.com/u/1342004?v=4",
        "resourcePath": "/google",
        "url": "https://github.com/google"
      }
    },
    "facebookRepo": {
      "name": "react",
      "owner": {
        "id": "MDEyOk9yZ2FuaXphdGlvbjY5NjMx",
        "avatarUrl": "https://avatars3.githubusercontent.com/u/69631?v=4",
        "resourcePath": "/facebook",
        "url": "https://github.com/facebook"
      }
    }
  }
}
```

## Conclusion

I hope you enjoyed writing some GraphQL queries. If you are interested in further learning about GraphQL and getting a big picture overview of GraphQL, you can check out my course [GraphQL: The Big Picture](https://app.pluralsight.com/library/courses/graphql-big-picture/table-of-contents) on Pluralsight.

Resources:  
[https://graphql.org/](https://graphql.org/)  
[https://graphql.org/learn/](https://graphql.org/learn/)  
[https://www.graphql.com/](https://www.graphql.com/)

If you have any comments, please post your comments below and share this post with your team and friends.
* * * 
**Editor's note:** Seeing something wrong with this post? You can find the correct version [here](https://blog.logrocket.com/graphql-fragments-explained/).

## Plug: [LogRocket](https://logrocket.com/signup/), a DVR for web apps
 
![LogRocket Dashboard Free Trial Banner](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/1d0cd-1s_rmyo6nbrasp-xtvbaxfg.png?resize=1200%2C677&ssl=1)
 
[LogRocket](https://logrocket.com/signup/) is a frontend logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.
 
In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.
 
[Try it for free](https://logrocket.com/signup/).
* * *
The post [GraphQL fragments explained](https://blog.logrocket.com/graphql-fragments-explained/) appeared first on [LogRocket Blog](https://blog.logrocket.com).