The React ‘useContext’ hook

Julia Bier
4 min readApr 12, 2022

--

Many times when developing React applications we have the need of sharing some kind of information between multiple components. For instance, imagine a large e-commerce website that needs to share a shopping cart among all of its routes, and also among many components inside of each route. How would that work in a React application?

To understand the situation and how to solve the problem, let’s create a very simple application. Inside of the App, you have two components which should share the same theme. One of them is the ThemeChanger, and it has a button to toggle the current theme (if dark, set to light and vice versa). The other is the ThemeDisplayer, which simply says what the current theme is.

The way they were first created, as shown below, is by having a theme state inside of each one. Of course it doesn’t work as needed, because by toggling the theme in the ThemeChanger, we are not altering the state in the ThemeDisplayer.

The easiest way to share the same state between the two would be to use a technique referenced in the React documentation as “Lifting a State Up”, or declaring it in the closest parent component of both items. In this case, it would be the App component. Then, you can just pass the needed information as props to the children, as shown in the next image.

Lifting the state up works, and now both share the same theme state.

This solution works just fine for this example, even though it’s a little weird to declare a state in the App component. Think now of a large application, with hundreds of components sharing dozens of states, all declared in the App and passed as props. Souds messy, right? No worries, we have an alternative for that.

React offers the function ‘createContext’, which returns a Context object. From this object we can create a Provider, a React component which passes to all of its children a set of values. Here, we create the ThemeContext, initializing it to an empty object, and also the ThemeProvider component, which will wrap all of the components that need to know the passed data.

Now, every component has access to the data passed in the “value” property, and it can be accessed with the ‘useContext’ hook. Or, we can add a new layer of abstraction to improve readability and create our own hook around the useContext, in this case useTheme (hooks always start with ‘use’).

Now it is very easy and semantically intuitive to use any of the properties passed to value. See how the ThemeChanger and ThemeDisplayer use it:

And this is how we can use the React Context API to share information between any components we wish. There are other tools we can use, such as Redux, but it goes beyond the scope of this article.

--

--