This content originally appeared on DEV Community and was authored by yqgoh
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
This content originally appeared on DEV Community and was authored by yqgoh

yqgoh | Sciencx (2021-11-09T02:40:21+00:00) React UseContext is Simple. Retrieved from https://www.scien.cx/2021/11/09/react-usecontext-is-simple/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.