What is React Context?

Kame House
2 min readSep 20, 2021

You Imagine that you live in a build of 20 floors your floor is 10th and you has a gas leak so you try to advisor to all neighborhoods you need run on stairway floor to floor(You don’t have a phone) so is possible that in the lasts floor you are tired without talking about the time that It takes.

In react the concept is similar with the context, the message of a gas leak is props and the floors are components. A message or props should pass from component to component.

Without context we need to pass our props component to component (notice that I use react with typescript):

Where Box and Bar are components that receiver the theme and Button dispatch the event to change the theme.

We pass theme props to our children component, in this case, are 2 but is possible that they are centenaries and this with one level and if we need pass props to component deeper around 3 or 4 levels passing those props component to component — level to level… manage props types… 😫

Context to the rescue

First, ¿whats is react context?

Context: Is a form to share data that can be considered global, in others words, Context is a form to pass data from component to component without use props.

Provider: Every context object comes with a provider React component that allows consuming components to subscribe to context changes.

In our example, the message about a gas leak, imagine that you have a phone so your life is easier you don’t have to run floor to floor, with some messages or calls you can advisor to your build and bombers if is necessary.

In react you can use context to have using useContext hook from import { useContext } from 'react'; The following form:

The Idea is easy, first we need to create a context where we going to save our data and provider to components this context:

After we only consume the context using useContext this hook receives the context created the before step and returns the data saved in context.

I hope that this helps you.

--

--