Relay for Visual Learners

The Problem solved by Relay and GraphQL (for Visual Learners Who Respond Well To Cartoons)

We start with our new React Component, RedComponent.

Like most components, RedComponent needs some external data to render. RedComponent expects data with a certain shape, e.g an object with name, birthday and favouriteColor properties.

And let’s introduce our server, who will provide RedComponent with the data it needs.

Great! Ship it.

This works perfectly well — until we decide to introduce a new feature provided by GreenComponent, which will be rendered inside RedComponent. This is a key strength of React: component composability.

GreenComponent expects data too, but it needs a different shape. And because it's rendered by RedComponent, RedComponent has the responsibility of passing down that data to GreenComponent.

And remember: our server now needs to serve the data our new composition of components expects.

With a little work, we eventually get this working. But times change, and now we’re deprecating RedComponent for the latest in UI sophistication: BlueComponent. Again, this is React doing what React does best: cleanly composing new and existing components together.

But guess what? BlueComponent expects a different shape of data. So unless we make some changes server-side, our components aren't going to render properly!

And what if we build another client with different components, like a mobile client? We’ll have to add another endpoint to our server to satisfy those components’ data expectations.

I've been using the word 'expects' here, because there’s absolutely no way for the server to really know what shape of data our components need. In this setup, the responsibility to keeping the expectations of the components and the data provided by the server in sync belongs to the developer.

That's right: the developer is the one who has to remember whether all the endpoints are providing the right kinds of data to components, and update the server whenever any data requirements are changed. And in the real world, we’re going to be using a lot of components. It's going to mean a lot of repetitive, boring, disciplined work. And who wants any of that?

What we need is a way for components to stop expecting and to start declaring what data they need. And we'd need a way to make a server that understands these declarations and can intelligently compose them.

This utopian solution would look a little something like this:

This is what Relay and GraphQL does.

Of course they do a lot more than that: query validation, data caching, optimistic queries, etc. etc. — but the above is what I feel is Relay and GraphQL’s raison d'etre.

Now see how all the pieces fit together with an interactive diagram!