When to use useContext()?

Jinwon Park
2 min readFeb 1, 2023

In React.js, using useState() is fairly intuitive. If there is a piece of data that changes with interaction with user, you can put it in state.

For example, if I want to make a form that takes in name, phoneNumber, and birthday of a user, I can make component like below.

It is simple, and there is no need for useContext as of yet.

But let’s say you want to make three different UI components for receiving input. You can break down App component to three components called InputName, InputPhoneNumber, and InputAge.

React Docs suggest handling this by “lifting state up”.

Basically, App component controls the state, and passes down state and event handlers as props to each components.

Ok. This works fine. Still no reason to use useContext().

Let’s add a little bit of styling to it. Let’s say you want to use re-usable input component that has a styling of bottom line with “1px solid grey”.

InputName component would be changed like below.

Now I can realize some problem. As I modularize the components, I have to send down the states and event handlers to the most basic components.(React Docs call it “prop drilling”). This generates a lot of boilerplate codes and a lot of potential errors, as it is easy to forget about passing down props.

This is case when Context comes in handy. Context lets parent component provide data to entire tree below it. This way, the child components can request for data above the tree.

Next article, I will go more in depth on how to use ContextAPI.

--

--