Relay takes care of this problem. It makes it easy to fetch data from the server as part of your data flow. In order to do this, Relay needs to know what data each component needs from the server. This is where GraphQL comes in.

So let’s look at GraphQL. But first…

What is a graph?

You might think of a graph as the same thing as a chart, or the graphs you made on a graphing calculator. That’s not the kind of graph we’re talking about.

The kind of graph we’re talking about is a group of things that are connected to each other by relationships. These things and relationships have special names in graph theory. The things are called nodes and the relationships between them are called edges.

If that sounds unfamiliar, just think of a property chain. For example, user.friend[0].attending[0]. That’ another way of thinking about the same graph.

If you look at an app like Facebook, a graph is the most natural way to think about the data. There are lots of things, and lots of relationships between those things.

When you pull up a page on Facebook, it’s showing you a particular view of that graph. And each component on the page shows you a small slice of the graph.

So how do you make the connection between a component and the small section of the graph that it displays?

This is what GraphQL does. It makes it possible to indicate the small section of the graph that you want. This small section is called a fragment. The fragments combine to create a larger query.

Relay piggybacks on this capability—being able to combine multiple fragments into a larger query — to solve a problem.

The problem

So what is the problem that Relay solves using GraphQL?

When you build React components, it’s easy to reuse them across different parts of your site. This is one of the main benefits of React. It’s called composability.

If your component needs to use data from the server, though, it gets harder to just drop a component in place. The server needs to know what properties the component needs. In many apps, this will be hard-coded on the server. There will be a URL (called an endpoint) that passes down data for that particular view. The endpoint code will know exactly what properties its view needs.

The problem here is that whenever you add (or remove) properties from the component, you have to change the server code too. This is called coupling; when you change one, you have to change the other, too.

Because you have to manually keep these two in sync, it makes bugs and obsolete code more likely.