Introducing the React Context API

  • The new React Context API is touted (at least on Twitter and a number of articles) as solving the need to use a state management tool, when I think in reality what it solves is easy dependency injection: Take something that lives at the top of your app and directly…
  • It essentially gives you an easy way to have state live at the top level in your component tree ( in this case) but “inject” it as a prop in a lower level component in the state tree.
  • A Consumer works hand-in-hand with the Context’s Provider, essentially allowing you to reach into your Context, and easily inject the Context’s value into a component, skipping many levels in the component tree.
  • Now that we’ve set up our Context and have created the Provider which wraps our app at the top level, we can now inject its into any of our lower level components.
  • When thinking of how to organize an app which uses React Context, I wanted to avoid having the Consumer code in the same file as the component which it “wraps”… the reason for this is because it makes it difficult to test the component in isolation.

We’ll take a look at the new React Context API, how to use it, what it does, and if it should replace Redux or MobX for your go-to state management option.

The new React Context API is touted (at least on Twitter and a number of articles) as solving the need to use a state management tool, when I think in reality what it solves is easy dependency injection: Take something that lives at the top of your app and directly inject it into a lower level component without having to pass it all the way down.

The code used in the Gallery example further down can be found here. Credit to Marian Serna for creating the code which this example is based off of.

Michel Weststrate, the creator of MobX says:

context is not a state management mechanism but more DI. It didn’t change anything in term of what is possible, just cleaned and finally formalized the api. So imho the answer to that question is the same as in React 16.2

Let’s start with a scenario fairly common in React, where you have your state living at the top level of your app. Let’s look at a simple component tree below:

In this scenario we’d most likely have our state live in the

App

component and we’d have to pass down the user’s information 2 levels to display it in the

component and 3 levels to display it in

. Now let’s say

wants to update the state, you’d have to pass a function from…

Introducing the React Context API