DEV Community

Cover image for How to use React Context API
Anurag Gharat
Anurag Gharat

Posted on

How to use React Context API

Passing data down the Multiple layers of components in React is a tough. React’s useContext() hooks makes passing data from Parent Component and consuming it in a child component easy. useContext() hook belong to the Context API which is used for state management in React.

What is React Context API?

React Context readily makes data available to the components without manually passing it through the entire component tree. Context API is a simple alternative to Redux library. Both are used for Central state management. You can read about Redux in my other blog here.

Using Context you can maintain a central state and pass it in the form of props and extract it in the components where you need. This solves the problem of Props drilling.

How to use React Context API.

Using the Context API in React is a 3 Step Process.

  1. Create the Context
  2. Provide the Context
  3. Consume the Context

Create the Context:

In the first step we create a context using the createContext(default) function. This function takes a optional parameter which is the default value.

import React from 'react';

const ApplicationContext = React.createContext()
Enter fullscreen mode Exit fullscreen mode

The ApplicationContext object contains two properties, Provider and Consumer. Provider to provide the context(data) and consumer to consume the context(data).

Provide the Context:

Once we create the context, we wrap the child components inside the Provider. While wrapping we pass our central state values which we wish to consume in our child components. This value can be a String, Number or even an Array or Object. Here we are passing “Anurag” as a value. Here Main is the Component which contains further Component tree.

<ApplicationContext.Provider value="Anurag">
      <Main/>
</ApplicationContext.Provider>
Enter fullscreen mode Exit fullscreen mode

Here is how my App.js file looks like after first two steps.

import React, { useContext } from "react";

const ApplicationContext = React.createContext();

export default function App() {
  return (
    <ApplicationContext.Provider value="Anurag">
      <Main />
    </ApplicationContext.Provider>
  );
}
Enter fullscreen mode Exit fullscreen mode

Consume the context

Now use the Consumer in the Child component of the Component Tree to extract the copy of the state data. You can extract the data in two ways, using Consumer Component or by using the useContext() hook.

Using <ApplicationContext.Consumer/> :

 <ApplicationContext.Consumer>
          {user =><h1>{user}</h1>}
 </ApplicationContext.Consumer>
Enter fullscreen mode Exit fullscreen mode

Using useContext() :

function Profile(){

  const user = useContext(ApplicationContext);

  return (
    <div>
      <p>Username : {user}</p>
      <UserCard />
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

Here is a complete example. Create a new react project add the following code in App.js. I have implemented the child components in the same file for simplicity.

import React, { useContext } from "react";

//Creating Context
const ApplicationContext = React.createContext();

export default function App() {

// Wrapping the Main component in Provider and passing the value
  return (
    <ApplicationContext.Provider value="Anurag">
      <Main />
    </ApplicationContext.Provider>
  );
}

function Main(){
  return(
    <div>
      <Profile/>
    </div>
  )
}

function Profile(){

//Using useContext()
  const user = useContext(ApplicationContext);

  return (
    <div>
      <p>Username : {user}</p>
      <UserCard />
    </div>
  )
}

function UserCard() {

//Using Context
    return(
      <div>
        <ApplicationContext.Consumer>
          {user =><h1>{user}</h1>}
        </ApplicationContext.Consumer>
      </div>
    )
}
Enter fullscreen mode Exit fullscreen mode

Output:

Output

Few important points to consider while using Context API:

  1. Provider can only hold one value, and the value can be anything.
  2. Only the Components that consume the data will re render on data change.
  3. You will have to export the created Context.
  4. You can create multiple contexts.

How to pass multiple value in Provider?

We can pass anything in the value prop of context, but we can pass only one prop. So in cases where you wish to pass multiple prop values in the Provider, you can club them together into one value variable and pass that as a prop.

Take a look at this example.

import React, { useContext } from "react";

const ApplicationContext = React.createContext();

export default function App() {

function changeUser(){
    //
}
const numbers=[1,2,3,4];
const obj = {name:"Anurag",id:101}

  return (
    <ApplicationContext.Provider value={{numbers,obj,changeUser}}>
      <Main />
    </ApplicationContext.Provider>
  );
}
Enter fullscreen mode Exit fullscreen mode

Are Context API and Redux the same?

The answer is no. Context API and Redux aren’t the same even if they solve the same problem i.e Prop Drilling. Context API is a simple alternative of Redux and should be used in places where Redux will be a overkill. Redux is a complete State management library which comes with features like middlewares, Reducers, Dev tools etc. Use Context API where you wish to avoid passing state through various Component levels.

Thanks for reading! If you love such content make sure you follow me on twitter. I post regular content on Web Development and Programming.

Top comments (0)