Introduction to useContext() Hook In ReactJS

Introduction

In the previous article, we have learned about useEffect() hook and how to fetch data using API using useEffect(). In this article, we will be learning about the useContext() hook. 

What is React Context

In React, suppose we have parent component  having 3 levels of child components,

useContext() Hook In ReactJS

Like the above image, if we want to pass any data from parent component to child component C, so as per React we need to pass props to each level to be available to Child component c.

This solution may be feasible when a number of child components are many. So, React hooks provides a concept call Context. 

React Context API allows you to easily access data at different levels of the component tree, without passing prop to every level as we have seen in the previous series by creating context, now in this, it will be achieved using useContext() hook. 

useContext() hook

This hook is used to pass data from one component to another without being specified to each of the component trees. 

Let’s look at the demo, 

Create a hierarchy as per the above image. Create 4 functional components, 

ChildC.js

import React from 'react'  
  
function ChildC() {  
    return (  
        <div>  
            Child Component at level 3  
        </div>  
    )  
}  
  
export default ChildC

ChildB.js

import React from 'react'  
import ChildC from './ChildC'  
  
function ChildB() {  
    return (  
        <div>  
            <ChildC/>  
            Child Component at level 2  
        </div>  
    )  
}  
  
export default ChildB 

ChildA.js

import React from 'react'  
import ChildB from './ChildB'  
  
function ChildA() {  
    return (  
        <div>  
            <ChildB/>  
        Child Component at level 1  
        </div>  
    )  
}  
  
export default ChildA

ParentComponent.js

import React from 'react'  
import ChildA from './ChildA'  
  
function ParentComponent() {  
    return (  
        <div>  
            <ChildA/>              
        </div>  
    )  
}  
  
export default ParentComponent 

and import in App.js

import React from 'react';  
import './App.css';  
import ParentComponent from './components/ParentComponent';  
  
function App() {  
  return (  
    <div className="App">  
      <ParentComponent/>  
    </div>  
  );  
}  
  
export default App; 

Now to create we have 3 steps, First, create a context in App.js. 

Provide value using <UserContext.Provider>. 

Use value of context using <UserContext.Consumer>. 

Create context object and pass the value in App.js as below.

import React from 'react';  
import './App.css';  
import ParentComponent from './components/ParentComponent';  
  
export const UserContext = React.createContext()  
  
function App() {  
  return (  
    <div className="App">  
      <UserContext.Provider value={'ReactApp'} >  
      <ParentComponent/>  
      </UserContext.Provider>  
    </div>  
  );  
}  
  
export default App;

and consume value in ChildC.js

import React from 'react'  
import {UserContext} from '../App'  
  
function ChildC() {  
    return (  
        <div>  
            Child Component at level 3  
            <UserContext.Consumer>  
                {  
                    user => {  
                        return <div>Context value is {user}</div>  
                    }  
                }  
            </UserContext.Consumer>  
        </div>  
    )  
}  
  
export default ChildC  

The output will display as below.

useContext() Hook In ReactJS

Now, let’s see how multiple values can be consumed using context.

import React from 'react';  
import './App.css';  
import ParentComponent from './components/ParentComponent';  
  
export const UserContext = React.createContext()  
export const CategoryContext = React.createContext()  
  
function App() {  
  return (  
    <div className="App">  
      <UserContext.Provider value={'ReactApp'} >  
        <CategoryContext.Provider value={'Programming'}>  
          <ParentComponent />  
        </CategoryContext.Provider>  
      </UserContext.Provider>  
    </div>  
  );  
}  
  
export default App;   

Now, import CategoryContext in ChildB.js.

import React from 'react'  
import ChildC from './ChildC'  
import {CategoryContext} from '../App'  
  
function ChildB() {  
    return (  
        <div>  
            <ChildC/>  
            Child Component at level 2  
            <CategoryContext.Consumer>  
                {  
                    category => {  
                       return <div><b>Category is {category}</b></div>  
                    }  
                }  
            </CategoryContext.Consumer>  
              
        </div>  
    )  
}  
  
export default ChildB 

The output will be displayed as below.

useContext() Hook In ReactJS

Now, we will import the CategoryContext in ChildC.js to see how nested consumer works.

import React from 'react'  
import {UserContext,CategoryContext} from '../App'  
  
function ChildC() {  
    return (  
        <div>  
            Child Component at level 3  
            <UserContext.Consumer>  
                {  
                    user => {  
                        return(  
                            <CategoryContext.Consumer>  
                                {  
                                    category=>{  
                                        return <div><b>Context value is {user} and Category value is {category}</b></div>  
                                    }  
                                }  
                            </CategoryContext.Consumer>  
  
                        )   
                    }  
                }  
            </UserContext.Consumer>  
        </div>  
    )  
}  
  
export default ChildC   

Now, it will display the output as below.

useContext() Hook In ReactJS

As in the above example, we have seen how to consume the context, we need to approach multi-level nesting, but it is very difficult to read and understand so to make it more readable, here, we will make use of the useContext() hook. 

Let’s see a demo of useContext() to use context value in a more readable and understandable format, The process of passing creating context and passing value remain the same; we just need to make changes while consuming values. 

Update code in ChildB.js to consume context value.

import React,{useContext} from 'react'  
import ChildC from './ChildC'  
import {UserContext,CategoryContext} from '../App'  
  
function ChildB() {  
    const user = useContext(UserContext)  
    const category = useContext(CategoryContext)  
    return (  
        <div>  
            <ChildC/>  
            Child Component at level 2  
            <div><i>User is {user}, Category is {category}</i></div>  
              
        </div>  
    )  
}  
  
export default ChildB 

As we can see in the above code, we just need to import useContext and after assigning the user.

Add Context and CategoryContext value to constant variables and we can simply use it as seen above.

The output is displayed in italics as below.

useContext() Hook In ReactJS

Using the useContext() hook makes code more readable and simpler to use. 

Summary

In this article, we have learned about useContext() hook and how it works in React. Now in the next article we will learn about useReducer() hook.

Any question or feedback or suggestion, please do comment and let me know.

One comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s