The Future of State in React

The days of relying on external libraries for managing light non-local state are coming to a close. React’s new Context API will be the go-to solution for sharing state simply™️.

In this post, I’ll describe Context by creating a simple theme-switching component:

Since Context won’t be live until React 16.3, I’ll be using the create-react-context polyfill. Whenever you see create-react-context referenced, you can basically substitute it with React.createContext.

Creating Context

Creating a Context instance is as simple as calling a function with a default value React.createContext(<default>).

Here’s an example:

API (Aesthetic Programming Interface)

The context API consists of only two parts: the Provider and the Consumer. Simple, right? I think so.

Provider

The Provider enables any child component in its tree to access its value. Context's Provider has less emphasis on global state than Redux and can be used to as little or as large a scale that you'd want: just like MobX.

In the following snippet, I set up a React Component that manages the state that our Provider will pass to those willing to consume it:

Consumer

Consumers must be descendants of its context’s Provider for it to access the value it wants. It’s similar to connect in Redux and observer in MobX, but in the form of a component with the famed Render Prop pattern instead of being a higher-order component.

Putting it all together

Now that we’ve established a core understanding of how Context works, play around with some code and toggle some themes!

If you found this post useful, make sure to follow me on Twitter and share this with your friends! ⚡️

Like what you read? Give Juwan Wheatley a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.