Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

React Context API

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 level of component tree, without using props to every single level.

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

Typically, in react application, data is passed from top to bottom with the help of props. But it becomes more complicated when we try to pass the data using props in 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?

React Context API

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

Now, let’s assume Child Component C wants to access data from parent component. Then in the traditional way, 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 which don’t actually need that data. You can imagine it at 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 the component C or to the needy component.

React context API: How it works?

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

We simply, create a createContext which have provider and consumer. Then we can send the data using provider component, and we need to import this component in the needy component then after we can use 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 which 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 only used when there is no matching provider available.

Context.Provider

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

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

The Provider component receives a prop called value, 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. And Consumer component is used to fetch the data from 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 component tree hierarchy, where we have 3 components and our parent component is App.js component. App component has imported ComA component, ComA component has imported ComB Component, and finally ComB component has imported ComC. So simply, it is our component tree.

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

We have to pass the data which is going to be shared with other component inside the Provider component. And 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 Consumer component using Firstname.

Now you might be thinking how it is possible that Consumer component can be accessed because in ComC we didn’t import createContext. So as we discussed earlier, Firstname is our context object, which have provider and consumer component, so that 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

React Context API

Check out video reference here:

Default image
reactjsguru
Articles: 44

Leave a Reply

Your email address will not be published.