Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

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

Posted on • Edited 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

importReact,{createContext}from"react";importComponentCfrom"./components/ComponentC";exportconstUserContext=createContext();
Enter fullscreen modeExit 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.

importReact,{createContext}from"react";importComponentCfrom"./components/ComponentC";exportconstUserContext=createContext();exportdefaultfunctionApp(){Letuser=johny;return(<divclassName="App"><UserContext.Providervalue={user}><ComponentC/></UserContext.Provider></div>);}
Enter fullscreen modeExit 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'importReact,{useContext}from"react"functionComponentF(){constuser=useContext(UserContext);return(<div>     Hello!!{user}</div>);}exportdefaultComponentF;
Enter fullscreen modeExit 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.Providervalue={'Hello'}><ChannelContext.Providervalue={'world'}><ComponentC/></ChannelContext.Provider></UserContext.Provider>
Enter fullscreen modeExit fullscreen mode

Following is the complete code inside App.js

1.)App.js

importReact,{createContext}from"react";importComponentCfrom"./components/ComponentC";exportconstUserContext=createContext();exportconstChannelContext=createContext();exportdefaultfunctionApp(){return(<divclassName="App"><UserContext.Providervalue={'Hello'}><ChannelContext.Providervalue={'world'}><ComponentC/></ChannelContext.Provider></UserContext.Provider></div>);}
Enter fullscreen modeExit 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'importReact,{useContext}from"react"functionComponentF(){constuser=useContext(UserContext);constchannel=useContext(ChannelContext);return(<div>{user}-{channel}</div>);}exportdefaultComponentF;
Enter fullscreen modeExit 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 moreLink

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

Top comments(2)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
lalami profile image
Salah Eddine Lalami
Hi I'm Salah Eddine Lalami , Senior Software Developer @ IDURARAPP.COM
  • Location
    Remote
  • Work
    Senior Software Developer at IDURAR
  • Joined

@ 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)

CollapseExpand
 
srishtikprasad profile image
Srishti Prasad
Javascript || Node Js || Express || mongoDB || DBMS || NoSQL || C++
  • Email
  • Location
    India
  • Education
    BTech @ National Institute of Technology Bhopal, India
  • Work
    Software development Engineer
  • Joined

👏👏nice!!@lalami

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Javascript || Node Js || Express || mongoDB || DBMS || NoSQL || C++
  • Location
    India
  • Education
    BTech @ National Institute of Technology Bhopal, India
  • Work
    Software development Engineer
  • Joined

More fromSrishti Prasad

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp