January 29, 2023

Blog @ Munaf Sheikh

Latest news from tech-feeds around the world.

What is context API in React? Example Tutorial


Introduction

Props and state are essential parts of a React component. While the state is controlled within the component, props are passed to it from the parent component. In a huge React application, a global state is generally created to pass the data around. Through props can also be used to pass data around multiple components but that can lead to unwanted situations. To avoid such unwanted situations, React provides the Context API. In this article, we will discuss what Context API is and how (and why) it is used.


Why use Context API?

Before discussing what is the context API, let’s discuss why to use it. Suppose we have a React application with five components – ComponentA, ComponentB, ComponentC, ComponentD, and ComponentE. Following is the structure of the application.

ComponentA

|

ComponentB

|

ComponentC

|

ComponentD

|

ComponentE

So here, ComponentB is the child of ComponentA, ComponentC is the child of ComponentB and so on. 

Now suppose we have an object that we need to pass from ComponentA to ComponentE. How to do this? Create a global state using Redux? Well, Redux is generally used for complex state management in bigger React applications and this is not the situation in this example.

Another way is to pass the object from ComponentA to ComponentB and then from ComponentB to ComponentC and then from ComponentC to ComponentD, and finally from ComponentD to ComponentE. This method will work too but the object has an unnecessary presence in three components. Such passing of props is known as Prop drilling. 

To avoid the usage of state management libraries and especially to avoid prop drilling, React provides Context API.

What is Context API?

In simple terms, Context API is a way using which data can be shared among components without passing it through props or creating a global state. So if there is an object in ComponentA, we can pass it directly to ComponentE without involving other components or redux. 

So let’s understand the Context API in React with the help of an example. 

Observe the following component.

import ComponentB from “./ComponentB”;

function ComponentA() {

  const emp = {

    name: “Johny”,

    age: 21,

    city: “Chicago”,

  };

 

  return <ComponentB />;

}

 

export default ComponentA;

“ComponentB” is the child of the above component. Similarly, “ComponentC” is the child of “ComponentB”. This is the structure we discussed earlier. So “ComponentE” is the last component in the tree. 

“ComponentA” has an object named “emp” and we will use this object in “ComponentE” by using context API.

Let’s start by creating a context in a separate file.

import React from “react”;

const AppContext = React.createContext();

 

export default AppContext;

“`

 

We will use “AppContext” in “ComponentA”.

 

“`

import ComponentB from “./ComponentB”;

import AppContext from “./AppContext”;

function ComponentA() {

  const emp = {

    name: “Johny”,

    age: 21,

    city: “Chicago”

  };

 

  return (

    <AppContext.Provider value={{ empDetails: emp }}>

      <ComponentB />

    </AppContext.Provider>

  );

}

 

export default ComponentA;

“ComponentA” is a provider, so we have to wrap the component in “Provider” using the “AppContext”.

<AppContext.Provider value={{ empDetails: emp }}>

  <ComponentB />

</AppContext.Provider>;

Here, we are passing “value” as an attribute. This attribute can be accessed in any component now. Let’s move to “ComponentE”.

“ComponentE” is the consumer. We can consume the value provided by the provider using two ways:

  1. By using “Consumer” provided by context API.

  2. By using useContext react hook.

The useContext hook is the easier and better way. So let’s use this hook to access the value in “ComponentE”.

import { useContext } from “react”;

import AppContext from “./AppContext”;

 

function ComponentE() {

  const context = useContext(AppContext);

 

  return <> </>;

}

 

export default ComponentE;

The “AppContext” is passed as an argument to useContext hook and saved in a variable. Let’s console the variable and see what it contains.

It contains the same object we defined in the “ComponentA”. Let’s access the values in “ComponentE” and check the output in the browser.

import { useContext } from “react”;

import AppContext from “./AppContext”;

 

function ComponentE() {

  const context = useContext(AppContext);

 

  return <>

    <h1> Name: {context.empDetails.name} </h1>

    <h1> Age: {context.empDetails.age} </h1>

    <h1> City: {context.empDetails.city} </h1>

  </>;

}

 

export default ComponentE;

Output:

What is context API in React? Example Tutorial

This is how context API is used in React to pass the data.

Summary

Using Context API is easy and simple. First, we have to define a context API. Then, we have to wrap the provider component in a “Provider”. Using the “Provider” provided by context API, we have to specify the attribute that contains the data which is used to pass around.

After that, in the consumer component, we have to use, either useContext hook or the “Consumer” provided by context API to access the value passed by the provider component. 



Source link