Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

How to Work With The React Context API

In this part, we will see about react context API. So react context API is a concept provided by react hooks, React context API allows us to easily access data at different levels of the component tree, without using props for every single level.

Simply, with the help of context API, data can be accessed by those components that are not connected to the parent component directly.

Typically, in a react application, data is passed from top to bottom with the help of props. However it becomes more complicated when we try to pass the data using props in a higher level of hierarchy. So for this problem, context API gives huge value and provides the best performance as well.

Why We Required to Use Context API?

How to Work With The React Context API

So we have an example here, As you can see we have a parent component that has a child component, Also this child component has another child component.

Now, let’s assume Child Component C wants to access data from the parent component. Then traditionally, the parent component passes its data using props to component A, and component A passes it to component B then component B passes it to component C, which is called prop drilling.

So as you can see, this is the issue because data is passed through two components that don’t need that data. You can imagine it at a higher component tree with like 10 components, then you have to pass that data through these components.

But Context API provides us the functionality to pass the data directly to component C or the needy component.

React context API: How does it work?

Firstly, we require React.createContext which returns a consumer and a provider. As the name suggests, a Provider is a component that provides the state to its children. It, simply, holds and stores data. Consumer as its name suggests consumes the provided data.

We simply, create a createContext which have providers and consumers. Then we can send the data using the provider component, and we need to import this component into the needy component then we can use the consumer to get the data in that needy component.

How to use React Context API?

React.createContext

import React, { createContext } from "react";
const UserContext = createContext(defaultValue);

With these lines of code, we can create an object of createContext. When a component gets a render that subscribes to this context object, then it simply reads the current value of createContext from the closest matching provider.

It also has a defaultValue argument which is only used when there is no matching provider available.

Context.Provider

<UserContext.Provider value={/* some value */}>

The context object comes with a Provider component, which allows other components to consume the data using the Consumer component. This one Provider can have many Consumers who can get data from it.

The Provider component receives a prop called, which is accessible by consumers.

Context.Consumer

<UserContext.Consumer>
  {(values) => <h1>{value}</h1>}
</UserContext.Consumer>

To access provider data in consumer, we need to first export the data values. The consumer component is used to fetch the data from the provider.

Note that: Provider and Consumer are the pre-defined components which are already defined in createContext.

React Context API Example

Now let’s understand the context API with a very basic and simple example:

App.js

import React, { createContext} from 'react';
import ComA from './ComA';

const Firstname= createContext();

const App =() =>{
  return(
    <>
      <Firstname.Provider value={"ReactJS Guru"}>
        <ComA />
      </Firstname.Provider>
    </>
  );
};

export default App;
export { Firstname };

ComA.js

import ComB from './ComB'

export default function ComA(){
    return(
    <>
        <ComB />
    </>);
}

ComB.js

import ComC from './ComC'

export default function ComB(){
    return(
    <>
        <ComC />
    </>);
}

ComC.js

import {Firstname} from './App'

export default function ComC(){
    return(
    <>
        <Firstname.Consumer>
            { (fname)=>{
                return(<h1>My Name is {fname}</h1>);
            } }
        </Firstname.Consumer>
    </>);
}

Now as you can see, we have here a component tree hierarchy, where we have 3 components and our parent component is the App.js component. App component has imported the ComA component, the ComA component has imported the ComB Component, and finally ComB component has imported ComC. So simply, it is our component tree.

Now, we need to pass data to the ComC component from the parent component. For that, we have imported, and also we have made an object of it inside the parent component. Then after, we accessed the provider component with the help of Firstname.Provider. Here, Firstname is our context object, and we can call us Provider with “.” operator.

We have to pass the data that is going to be shared with another component inside the Provider component. Finally, we have exported that Firstname within the curly braces {}.

Now we don’t need to touch ComB and ComC when we use context API. We will directly jump on the ComC component. Here we have imported our Firstname object, after that, we have just called the Consumer component using Firstname.

Now you might be thinking how it is possible that the Consumer component can be accessed because in ComC we didn’t import createContext. So as we discussed earlier, Firstname is our context object, which has provider and consumer components, so we don’t need to import createContext here.

After that, we just need to call the Consumer component. This Consumer component always takes a function, this is why we have used a callback function, which again has a return statement.

Output

How to Work With The React Context API

Check out the video reference here:

Reactjs Guru
Reactjs Guru

Welcome to React Guru, your ultimate destination for all things React.js! Whether you're a beginner taking your first steps or an experienced developer seeking advanced insights.

React tips & tutorials delivered to your inbox

Don't miss out on the latest insights, tutorials, and updates from the world of ReactJs! Our newsletter delivers valuable content directly to your inbox, keeping you informed and inspired.

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents