Using React’s New Context API with Relay
React recently released their new Context API and it already seems to be gaining traction in the community.
The basic idea is that you set some data at the top of a component tree and can access that data at the bottom of the tree without having to pass it through every component in the middle as a prop.
In the example above, the Grandparent
can pass its name to the Child
without drilling the prop through the Parent
component sitting between them. When the Grandparent
provides a value, and then any component in that tree can consume that same value.
We’re not in favor of changing to something new just because it looks shiny, but we found that this approach was intuitive and would be straightforward to use. Also, the old, experimental Context API is being deprecated starting with React 17, so anyone lagging behind will have to learn soon!
The first way we’ve found to make the new Context API useful is in tidying up how we handle our mutations in Relay. Every mutation requires that you pass it a Relay Environment, which “bundles together the configuration, cache storage, and network-handling that Relay needs.”
So using the Context API, we provide that environment
to components like this:
In this simplified setup, the withData
component provides the Relay environment, and the UIButton
component consumes it.
By using the Context API, we easily set up our Relay environment in one place and then can access that environment in any component that needs to call a mutation. We’re looking forward to finding lots more ways to make this great new feature useful!