How to use React Context API

BH Nibir
3 min readMar 29, 2020

--

Today we are going to learn how to use React Context API.

React Context API

Why Use Context API?
In general, React application, data is passed top-down (parent to child) via props, but if you want to share your data parent component to multiple nested child components? Here comes React Context to solve this problem.

React Context is designed to share data that can be considered “global” for a tree of React components

The problem we’re trying to solve
Before solving the problem, let me describe the problem scenario first.

Let’s say that we have a userName in the App component and a child User Component who has two nested children component which is Menu and Profile components.

I want to show the userName in Child Menu and Profile Component.

Let’s start

First, start a new React project using create-react-app cmd.

Then let’s create all the components:

src/App.js

If we run the app (npm start), then we’ll see

localhost:3000

Now create A Context?

Step One: Creates a Context object.

createContext

The createContext method import from React library and store in UserContext Variable.

Step Two: Passing value by Provider object

Provider component has a prop — value - which allows us to pass data assigned to this prop to all descendants (in value we can pass an object, number, function, etc...).

User component is wrapped by Context.Provider, and without props, all children component under the User component can access the data which we passed to value prop in Provider.

Step Three: Now we are going to using useContext Hook to access shared data.

Menu Component

Here we import useContext hook and pass UserContext to get data which data we share from App Component and store it in a userName variable. Then show the userName in h3 tags.

Also, use useContext hook in another nested child Profile component for getting data.

Profile Component

Now see the full Coding

full Coding

See final Output

Output

So, to use Context API in the app you need to follow the next steps:

  • create context — React.createContext()
  • provide context — YourContext.Provider
  • consume context — useContext(YourContext)

After that, You Share your data in any nested child components without using props.

And that’s it!

--

--