Why use UseContext?
React useContext hook is used to create global data that can be accessed throughout the component hierarchy without the need to keep passing the props down manually to each component level.
This process of manually passing props down each level of child components (even though some child level does not need the data) to eventually reach the target child component is called Prop Drilling. Using useContext can help resolve this tedious process of Prop Drilling!
Simplified code snippets
In Parent component or App.js, we just need to create & export the context, literally by using the createContext hooks! Simply use these few lines of code:
// in App.js
import {createContext} from 'react';
export const contextToPassDown = createContext();
Then wrap the context Provider over the child components you wish to provide the context
<contextToPassDown.Provider value={dataToPassDown}>
<ChildComponent />
</contextToPassDown.Provider>
Then in any Child components that are wrapped by the tag, we just need to use the useContext hooks!
// in ChildComponent.js
import {useContext} from 'react';
import {contextToPassDown} from App.js;
const ChildComponent=()=>{
const contextToUse = useContext(contextToPassDown);
return (<div> {contextToUse.username} </div>);
}
export default ChildComponent;
The use cases for useContext are usually:
- To Pass down logged-in user info to authorized components
- For 'light' or 'dark' theme
You may practice using this link to: codesandbox
Top comments (8)
Congrats on your second post! But I agree with @code913 , this is a pretty low quality post. Some tips for your next one:
Thanks for all the tips! I oversimplified the post!:)
@ 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...
I found this helpful. Thanks for posting.
Never use condescending language. It is toxic.
Thanks for the feedback! did not intend to be condescending! :)
thanks for the feedback!
rahmat menga yoqdi qisqa tushunarli qilibsiz