Samer Buna

GraphQL Fragments are the Best Match for UI Components

What are GraphQL fragments? What are UI components? Why are they a match?

To build anything complicated, the one and only truly helpful strategy is to split what needs to be built into smaller parts and then focus on one part at a time.

Ideally, those parts should be designed in a way that does not couple them with each other. They should be testable on their own and they should be reusable. The big complicated system should be the result of putting these parts together and having them communicate with each other to form features.

With User Interfaces, one strategy to do this splitting is by using UI components.

What exactly are UI components?

The word component can mean different things to different people. In the domain of User Interfaces, a component can be an abstract input text box or Twitter’s full tweet form. You can pick any part of an application and call that a component. They can be small or big. They can be functional on their own or they can just be parts that have to be put together to make something functional.

Bigger components can also be composed from smaller ones. The Twitter’s TweetForm component can be composed from a TextArea component with a TweetButton component, and a few other components to attach an image, add a location, and count the number of characters typed in the text area.

All HTML elements can be considered simple components. They all have properties and behavior but they are limited in the fact that they cannot represent dynamic data. The story of UI components gets interesting when we can make a component represent data. We can do that with modern libraries and frameworks.

Data Components

We can use many modern JavaScript libraries like React.js, Angular.js and Polymer.js to define UI components that represent data. These components can then be reused for any data that matches the shape they have been designed to work with. The components do not really care about what that data is. They are only concerned about the shape of that data.

The idea of rich components is actually coming natively to the browser with what is commonly labeled as Web Components. Many browsers already support most of the features needed to define and use Web Components. The Polymer.js project is designed to first provide polyfills to support using Web Components in any browser and then enhance their features.

Let’s assume we want to build an app like Twitter by using rich data components. I will take one example page from that app and analyze it in terms of components and their data requirements.

Let’s talk about the user’s profile page. It’s a simple page that displays public information about the user, some stats, and the list of their tweets.

For example, if you navigate to on Twitter, you will see something like:

The @manifoldco profile page at TwitterThe @manifoldco profile page at Twitter

I can see at least 15 components on this page:

  • The Header component, which includes the following list of components: ProfileImage, BackgroundImage, TweetCount, FollowingCount, FollowersCount, LikesCount, and ListsCount

  • The Sidebar component, which includes the following list of components: UserInfo, FollowersYouKnow, UserMedia, and MediaItem.

  • The TweetList component, which is a list of Tweet components.

Of course, this is just my choice of components. This page can be built with a lot more components and it can also be built with just two components. No matter how small or big the components that you design are, they will share a simple fact: they all depend on some shape of data.

For example, the Header component above needed a data object to represent a profile. The shape of that data object might look like:

1const profileData = {
2 profileImageUrl: ...,
3 backgroundImageUrl: ...,
4 tweetsCount: ...,
5 followingCount: ...,
6 followersCount: ...,
7 likesCount: ...,
8 listsCount: ...,

The TweetList component above needed a data object that might look like:

1const tweetList = [
2 { id: ...,
3 userName: ..,
4 userHandle: ...,
5 date: ...,
6 body: ...,
7 repliesCount: ...,
8 tweetsCount: ...,
10 },
11 { id: ...,
12 userName: ..,
13 userHandle: ...,
14 date: ...,
15 body: ...,
16 repliesCount: ...,
17 tweetsCount: ...,
18 likesCount: ...,
19 },
20 ...,

These components can be used to render information about any profile and any list of tweets. The same TweetList component can be used on Twitter’s main page, a list page, or the search page.

As long as we feed these components the exact shape of data that they need, they will just work. This is where GraphQL comes into the picture because we can use it to describe the shape of data needed by an application.

To simplify the Twitter example, I will consider that we are going to build the profile page with just these main four components: Header, Sidebar, TweetList, and Tweet.

Declaring Data Requirements

GraphQL is all about declaring data requirements. The whole language is designed for that purpose. We can write a single GraphQL query to ask for the data needed for an application.

Every application has data requirements. The data required by an application is the sum of the data required by that application’s individual components.

The cool thing about the GraphQL language is that it offers a way to split a big query into smaller ones. Just like we split an application into multiple components, we can split a GraphQL query into multiple fragments.

See the next section for an introduction to GraphQL fragments.

Do you see where I am going?

  • We have an application that is composed using components.

  • Every component has some data requirements.

  • We need a GraphQL query to declare all of that application’s data requirements.

  • We can split a GraphQL query into fragments.

This makes a GraphQL fragment the perfect match for a component! We can simply use a GraphQL fragment to represent the data requirements for a single component and then put these fragments together to compose the data requirements for the whole application.

Let’s do that for our example, but let me first make sure you know about the awesome power of GraphQL and its fragments.

What exactly are GraphQL fragments?

To ask a GraphQL server for data, we send it a query. A query is simply a nested set of fields.

Let me use GitHub for some examples. You can test all GitHub query examples below using GitHub’s GraphQL API Explorer.

Here is a GraphQL query you can use at GitHub to read some information about a user:

2 viewer {
3** login
4 company
5 avatarUrl**
6 }

The above query reads information about the currently authenticated user (hence the root field, viewer). However, you can use a similar query to ask for the same information for any user:

2 user(login: "ntassone") {
3** login
4 company
5 avatarUrl**
6 }

You can also use a similar query to ask for the same information for every user who made a commit to a repository, created an issue in a repository, or just star-gazed a repository. Here’s a query to list the star-gazers of a repository:

2 repository(owner: "manifoldco", name: "torus-cli") {
3 stargazers(first: 100) {
4 nodes {
5** login
6 company
7 avatarUrl**
8 }
9 }
10 }

If you notice, all three query examples below share something: the three bolded fields. Now imagine that we want to ask the server for data using all three queries at the same time (for some abstract reason).

The bolded fields would have to be repeated:

If we later decided to add another field to the list of these three common user fields, we would need to modify multiple places in the big query. This is where a GraphQL fragment can be useful. We can use them to avoid this repetition.

We first define a GraphQL fragment that represents the fields that are common between multiple queries. A GraphQL fragment has to be defined on a data type. In our examples, that data type would be a GitHub User:

1fragment UserInfo on User {
2** login
3 company
4 avatarUrl**

Now, everywhere we need to read these exact three fields for a user, we can use the UserInfo fragment instead of repeating them. To use a fragment, we spread it at the level where it is needed using the three-dots spread operator:


The abstract query that combines all three examples above becomes:

2 viewer {
3 **...UserInfo**
4 }
5 user(login: "ntassone") {
6 **...UserInfo**
7 }
8 repository(owner: "manifoldco", name: "torus-cli") {
9 stargazers(first: 100) {
10 nodes {
11 **...UserInfo**
12 }
13 }
14 }

Fragments can be defined on any type and we can nest them as well. Here is a bigger fragment that uses the smaller UserInfo fragment:

1fragment StarGazersInfo on Repository {
2 stargazers(first: 100) {
3 nodes {
4 ...UserInfo
5 }
6 }

Which means, the abstract query example can now be:

2 viewer {
3 ...UserInfo
4 }
5 user(login: "ntassone") {
6 ...UserInfo
7 }
8 repository(owner: "manifoldco", name: "torus-cli") {
9 ...StarGazersInfo
10 }

In summary, GraphQL fragments allow us to:

  • Reuse common parts of a GraphQL query

  • Compose a GraphQL query by putting together multiple fragments

    You can simply think of GraphQL fragments as the components of GraphQL queries.

Using GraphQL fragments for the Twitter example

Let’s come up with the data required by the Twitter’s profile page example above using a single GraphQL query for each component we identified.

The data required by the Header component can be declared using this GraphQL fragment:

1fragment HeaderData on User {
2 profileImageUrl
3 backgroundImageUrl
4 tweetsCount
5 followingCount
6 followersCount
7 likesCount
8 listsCount

The data required by the Sidebar component can be declared using:

1fragment SidebarData on User {
2 userName
3 handle
4 bio
5 location
6 url
7 createdAt
8 followersYouKnow {
9 profileImageUrl
10 }
11 media: {
12 mediaUrl
13 }

Note that the followersYouKnow part and media part can also come from the sub-components that we identified earlier in the Sidebar component.

The data required by a single Tweet component can be declared using:

1fragment TweetData on Tweet {
2 user {
3 userName
4 handle
5 }
6 createAd
7 body
8 repliesCount
9 retweetsCount
10 likesCount

Finally, the data required by the TweetList component is an array of the exact data required by a single Tweet component. So we can use the Tweet fragment here:

1fragment TweetListData on TweetList {
2 tweets: {
3 ...TweetData
4 }

To come up with the data required by the whole page, all we need to do is put these fragments together and form one GraphQL query:

1query ProfilePageData {
2 user(handle: "manifoldco") {
3 ...HeaderData
4 ...SidebarData
5 ...TweetListData
6 }

Now we can send this single ProfilePageData query to the GraphQL server and get back all the data needed for all the components on the page.

When the data comes back, we can identify which component requested which parts of the response and make those parts available to only the components that requested them. This helps isolating a component from any data that it does not need.

But this is not the coolest thing about this approach. By making every component responsible for declaring the data it needed, these components will have the power to change their data requirements when necessary without having to depend on any of their parent components in the tree.

For example, let’s assume Twitter decided to show the number of views each tweet has received next to the likesCount. All we need to do to satisfy this new data requirement is to modify the TweetData fragment:

1fragment TweetData on Tweet {
2 user {
3 userName
4 handle
5 }
6 createAd
7 body
8 repliesCount
9 retweetsCount
10 likesCount
11 **viewsCount**

None of the other components in the application need to worry about this change or even be aware of it. For example, the direct parent of a Tweet component, the TweetList component, does not need to be modified to make this change happen. That component always constructs its own data requirements by using the Tweet component’s data requirement no matter what that Tweet component asked for.

This is simply great. It makes maintaining and extending this app a much easier task.


Using rich data UI components to build big applications is a winning strategy. If you are using frameworks like Angular.js or React.js, you are already doing that.

All data components require some shape of data. You can use GraphQL to declare that shape. GraphQL queries can be composed using fragments. Fragments are to queries what UI components are to a full application. By matching every UI component in the application to a GraphQL fragment, we give these components the power of independency. Each component can declare its own data requirement using a GraphQL fragment and we can compose the data required by the full application by just putting these GraphQL fragments together.

That’s all I have for this topic. Follow me for more articles on GraphQL and its ecosystem. Thanks for reading!

Learning React or Node? Checkout my books:

About Manifold

Manifold is the first independent marketplace for developer services and the easiest way to manage and share everything from JawsDB, a simple postgres database to Mailgun, an API that makes sending and receiving email dead simple.

For more info visit or follow us on twitter. This post is part of the Manifold Content program. Want to write for us?

Stratus Background

Sign up for the Stratus Update newsletter

With our monthly newsletter, we’ll keep you up to date with a curated selection of the latest cloud services, projects and best practices.
Click here to read the latest issue.