DEV Community

Cover image for Guide to React Hook-useContext()
Srishti Prasad
Srishti Prasad

Posted on • Updated on

Guide to React Hook-useContext()

What is useContext hook?

useContext provides a way to pass data through the component tree(child component) without having to pass props down manually at every level.

Let’s understand using this flowchart

usecontext1

Let’s, consider username which is to be passed to level A,B,D straight forward but to pass to nested levels we have to pass it through intermediate level also that is if we want to pass it to level G we have to pass it as prop to its level D,E,F then it will go to G.

So, to avoid this passage of prop to every intermediate level ,we use useContext hook.

How to use useContext hook

Here I’ll consider rightmost part of flowchart
App
D
E
F
Goal is to pass username as prop from App component and read that in F component
Lets understand how to get data from App component to component F

The three steps which we need to keep in mind while using useContext Hook
1.Create context
2.Provide context with a value & the provider must wrap the children component for the value to be
available.
3.final step is to consume the context value

To do this, first create context, for that you must Import createContext and initialize it and then export context from app component.

App.js code

import React,{createContext } from "react";
import ComponentC from "./components/ComponentC";
export const UserContext = createContext();
Enter fullscreen mode Exit fullscreen mode

Note: we’re exporting the UserContext so we can import it
into nested components later.

Now, with that UserContext in place, we can wrap a provider around components, then consume the property in any child component. So, we’ll set that provider where we want it and pass it a property.

import React,{createContext } from "react";
import ComponentC from "./components/ComponentC";
export const UserContext = createContext();

export default function App() {
Let user=johny;
 return (
   <div className="App">
     <UserContext.Provider value={user}>
    <ComponentC/>
    </UserContext.Provider>
   </div>
 );
}

Enter fullscreen mode Exit fullscreen mode

Note that now, we’re not sending the user property into Profile. We’re sending it into the UserContext Provider via value={user}. We can then grab that value in any of the nested components.

Third and the last step is to consume directly in component F without passing it to intermediate component D & E
The useContext will return the value that we sent into UserContext.Provider value={user}

import {UserContext} from '../App'
import React,{useContext} from "react"
function ComponentF(){
 const user=useContext(UserContext);
 return(
     <div>
     Hello!! {user}
     </div>
 );
}
export default ComponentF;
Enter fullscreen mode Exit fullscreen mode

Now, you all might be wondering what if we have multiple context value that is to be passed through nested component?

Let's break it down

We will create another context named ChannelContext

export const ChannelContext=createContext();

Wrap this context provider inside the initial context provider

   <UserContext.Provider value={'Hello'}>
       <ChannelContext.Provider value={'world'}>
         <ComponentC/>
       </ChannelContext.Provider>
    </UserContext.Provider>
Enter fullscreen mode Exit fullscreen mode

Following is the complete code inside App.js

1.)App.js

import React,{createContext } from "react";

import ComponentC from "./components/ComponentC";

export const UserContext=createContext();
export const ChannelContext=createContext();

export default function App() {
 return (
   <div className="App">
     <UserContext.Provider value={'Hello'}>
       <ChannelContext.Provider value={'world'}>
         <ComponentC/>
       </ChannelContext.Provider>
    </UserContext.Provider>
   </div>
 );
}

Enter fullscreen mode Exit fullscreen mode

2.)Now, we can import the context created in the root component to any of the nested component .For that import useContext hook

import React,{useContext} from "react"

ComponentF.js

import {UserContext,ChannelContext} from '../App'
import React,{useContext} from "react"
function ComponentF(){
 const user=useContext(UserContext);
 const channel=useContext(ChannelContext);
 return(
     <div>
     {user}-{channel}
     </div>
 );
}
export default ComponentF;

Enter fullscreen mode Exit fullscreen mode

To view whole code source click on this link
(codeSandBox=>https://codesandbox.io/s/usecontext-react-hook-4ejrj5?file=/src/index.js)

I am sure concept of useContext hook must be clear and till now you must have understood how powerful this hook is. Moreover it can also be used together with the useState Hook to share state between deeply nested components more easily than with useState alone.
Here is the link you can visit to learn more Link

I you are reading till here give this article a like ❤️ and follow me for more content like this.

Top comments (2)

Collapse
 
lalami profile image
Salah Eddine Lalami

@ IDURAR , we use react context api for all UI parts , and we keep our data layer inside redux .

Here Article about : 🚀 Mastering Advanced Complex React useContext with useReducer ⭐ (Redux like Style) ⭐ : dev.to/idurar/mastering-advanced-c...


Mastering Advanced Complex React useContext with useReducer (Redux like Style)

Collapse
 
srishtikprasad profile image
Srishti Prasad

👏👏nice!! @lalami