Making Sense of useContext in React

Lucas Thinnes
3 min readSep 17, 2021

For those familiar with React Hooks, the heaviest hitters among them are unquestionably useState and useEffect, which are excellent state management tools that increase the efficacy and cleanliness of your projects almost to the point where they could be considered a necessity. For those who only familiarize themselves with these two, I wanted to offer a detailed (as detailed as I can be) explanation of the benefits of using Context in React to avoid the unnecessary overload of passing props down a massive chain of components.

THE CASE AGAINST PROP DRILLING

The idea of “prop drilling” is to pass properties down a hierarchy of components so that many different pieces of the application can have access to certain values. This is a reasonable thing to execute in an app with only a few components but as you can imagine, as things are scaled upward and outward to much larger projects, passing these downwards has a large margin for error and with those errors would come a lot of time wasted spent trying to debug where in the chain things went wrong.

CLARIFYING STATE

In React, “state” is essentially a collection of properties which control how the application looks and behaves. The individual traits which store data & information about each section are referred to as “props”. State can be thought of as the condition of the application, i.e. what has been rendered, what will be rendered when an operation is initialized or completed, and how the changes in what is rendered will affect the page. This is important to understand when it comes to the “useContext” hook, as the location of the properties and by extension their own state will exist auxiliary to the hierarchy of components which make up an application.

USECONTEXT IN PIECES

The context API is broken into 5 individual components:

  • React.createContext
  • Context.Provider
  • Class.contextType
  • Context.Consumer
  • Context.displayName

The createContext does what it implies, it creates the context. The creation of a context looks like this:

export const Context = React.createContext(defaultValue);

The Context const is exported so other components will have access to it.

The context provider is what contains the value which will function as a prop that will be available to all children components. An example looks like this:

<Context.Provider value={valueOfProps}>

The contextType is called upon React via React.createContext() and lets you use the nearest value of the context type using this.context.

The Context.Consumer gives you access to context within function components, and Context.displayName accepts a string and presents this string within the DevTools. More about these can be read over at the documentation here.

--

--