Let’s keep this post simple. I am going to scaffold a Relay component and an Apollo component. The goal here is to understand how each are structured and really show how they solve the same problem in different ways. What we are not going to show is the schema generation, or resolvers. Though, that is an excellent idea for a future blog post. What I want to get at is the component development experience.

The component we’re building:

Relay

So in the Relay world, we need to export a “container”, essentially a specific Relay wrapper around our components. What it will do is declare the GraphQL fragments we’re trying to resolve from the server and pass them as props to our component. This container looks something like this:

We then need to build a “Root Query” for the “Root Container” in Relay.

Let’s build our query.

And finally, we render it to the DOM.

Apollo

Now that we’ve scaffolded the component with Relay, let’s do it with Apollo. In Apollo we’ll take our SampleComponent and map our GraphQL queries right to the component. Apollo doesn’t have named fragment support, but it’s coming very soon. The intern is making major moves :).

If you like Redux, or use Redux, this will look extremely familiar to you.

In Apollo, we map the queries we want right to the component. Just like mapStateToProps in Redux.

Next, let’s build something similar to Relay’s Root container. Once again, much like Redux root components we’ll setup a Provider and render our component.

The interface to connect the client to our GraphQL server is found within the ApolloClient. This internally manages the state of our queries, mutations, and the data returned by our resolvers when querying data. The data is then pushed into a Redux store for convenient state management.

And thats it! You can use your handy dandy Redux dev tools to examine state changes.

Sample Dev Tools

Conclusion

Pretty cool right? This post was really to show you all the component level interface for connecting GraphQL queries. Both Relay and Apollo are great choices for building really dynamic product experiences!

Check them both out!