Sitemap
Ruth Newman

Ruth Newman

Using the React Context API

4 min readJul 21, 2019
Press enter or click to view image in full size
You can use the React Context API for many use cases where you may have sought out Redux, but with much less hassle and much less code!

Building on from my adventures with vanilla JavaScript, I have progressed to focus on the React library and gaining greater mastery of using a frontend framework (or library), such as React, with a JavaScript project.

React is not just about getting familiar with JSX, building components, and handling state and props, but also about using Redux, React-Redux, React Router, Testing and Styling React projects, React Hooks and more. Within this list of additional areas should also come the React Context API.

As with all my other recent blogs — I continue to recommend looking at the relevant official documentation either as a starting point to get stuck in or to as a reference point later on for clarification, or for a bit of both, whichever best suits where you are at and your learning pattern. You can find them here for Context.

Why use Context?

Well — Context can solve similar problems to those addressed by the use of Redux, but can help you avoid adding Redux to your project where it might not be necessary (and given the larger learning curve and substantial boilerplate involved with setting up Redux).

These kind of problems relate to state management and passing props between multiple components (e.g when passed beyond the one level of parent and child components, but to grandchildren, great-grandchildren and so forth). This traditional approach involves passing a lot of props, including to components that do not actually need these props themselves, but simply to pass them down the tree to the correct component you are targeting.

Redux addresses this problem by creating an external store where state is managed and through actions and reducers that update state.

React Context allows for the setting of ‘global’ values — i.e. data that can be accessed by all descendants within a component’s tree.

To get started and create a context — we need to use React.createContext() and set it to a variable, the argument will serve as the context’s default value, e.g. in a separate file in our React project (in this case named ‘ExampleContext.js’):

import React from 'react';const ExampleContext = React.createContext('medium-blog');export default ExampleContext;

In addition to creating our context, we need a Provider and a Consumer, which we can set and export as in the following examples:

export const ExampleProvider = ExampleContext.Provider;
export const ExampleConsumer = ExampleContext.Consumer;

What is a Provider and what is a Consumer?

Get Ruth Newman’s stories in your inbox

Join Medium for free to get updates from this writer.

Each Context object requires a Provider which ‘delivers’ the value requested from the context and ‘provides’ it to whichever component requires it.

Whilst you can only have one provider per context, it is likely you will have multiple Consumers. These are the components which request data from the provider and receives the stored information.

All Consumers must be descendants of the Provider.

import React, { Component } from 'react';
import ExampleProvider from './ExampleContext';
import Child from './Child';
class App extends Component {
render() {
return (
<ExampleProvider value="blog">
<Child />
</ExampleProvider>
);
}
}
export default App;

The child component meanwhile, doesn’t need to pass the props through ‘prop drilling’ as you might be used to already:

import React, { Component } from 'react';
import Grandchild from './Grandchild';
class Child extends Component { render() {
return (
<div>
<Grandchild />
</div>
);
}
}export default

The grandchild component — however — can access the value from the context through an approach that assigns a contextType such as in the following example:

import React, { Component } from 'react';
import Greatgrandchild from './Greatgrandchild';
import ExampleConsumer from './ExampleContext';
class Grandchild extends Component {

static contextType = ExampleContext;

render() {
return (
<ExampleConsumer>
<Greatgrandchild theme={this.context} />
</ExampleConsumer>
);
}
}

Overall reflections on getting started with React Context

On initial use the React Context API seems much less cumbersome and much more straightforward than using Redux, but I need to continue to build more projects with either React-Redux or with the Context API and become more astute as to which projects and code architecture and what works best with what. I know instinctively I’m much happier to naturally explore incorporating React Context in my upcoming React projects and will do so more naturally, quickly and confidently than I will with Redux for the time being. I feel more confident with both the theory of Context and with its practical use, in a way I can develop myself independently for upcoming projects without needing to copy a large amount of boilerplate code.

In short — React Context is accessible, a potential problem solver and worth giving a go!

--

--