Using React's new context API

Why context?

A component tree can quickly grow. The root component has many children, the children have many children and so on.


What if you want to pass information that is considered global to a tree or subtree of components? For example what language these components should use. Or what the username is.
You could use props of course, but it seems unnessary to pass on the same information over and over again to each component.

This is where the context comes in.

Pre context

In this example from the React website no context is used.


The theme with value dark is passed with a prop to the child toolbar component which passes it on to it's child ThemedButton also with a prop.

With context

Here's the example with context.


In the first line the context is created with just the string light in it which acts as the default value for this context. In this case it's just a string but it could be an object as well of course.

Also, right now the context is declared in the same file but you would typically export it from a module and import it in the seperate component modules. This example is just presented this way to make things clear.

The root level component tells the context that it is the provider of the value and it provides the value dark. Then it renders the toolbar component. The toolbar component itself doesn't do anything with the context but it renders a ThemedButton which uses the context and declares itself as a consumer of the value. The value is provided using an arrow function. So the value dark will be in the theme variable.
The ThemedButton passes this to a standard Button component with a prop.
Because the context has a default value a provider is not a must. Without it the ThemedButton would work with the light theme.

Why the complexity with provider and consumer?

Well, in this case the value set in the provider is kind of static but what if the value was dynamic? Because it was taken from state or a prop for example? Then the context would take care of updating the value automatically across all children. It will know exactly where to update the value because all the consumers of the value are known.

React Getting Started
Tweet Post Share Update Email RSS