Fragment Driven UIs with Apollo

Abhi Aiyer
Open GraphQL
Published in
4 min readJun 17, 2018

--

Today I want to share a cool pattern I’ve been using in my React Apollo applications.

I was working on a feature recently where I needed to fetch some user data to determine if the current user had a specific “role”. Based on that role, we would render you a UI component that only that role could view.

Pretty easy right? Because this component was deep in the application hierarchy we can take advantage of one of my favorite features in Apollo Client: caching.

Let me make a smaller example to show off:

In this simple example, we use react-apollo + recompose to connect our component that is found deep in our tree! This container can pass a fetchPolicy, but we pass cache-only as a default because this component is deep in a tree where the currentUser query has already been fetched.

This is a great solution and you can leverage all the best Apollo Client has to offer by calling different queries for different circumstances based on your UX. In this case, instead of passing props all the way down the component hierarchy, we can “connect” any component with data in our cache at any level.

When I approached this problem, I thought that there had to be a more semantic way to…

--

--