What is context?

In React, passing props down the component tree can become annoying, especially when a deeply nested component needs values from a higher-level parent. Passing properties down through components that don't directly use them is literally referred to as prop drilling.

const ParentComponent = () => { const [parentState, setParentState] = useState(20); return <MidComponent val={parentState} />; } const MidComponent = ({ val }) => { return <LowerComponent val={val} />; } const LowerComponent = ({ val }) => { return <div> Value is equal: {val}</div>; }

In the above example, the MidComponent accepts the val prop even though it doesn't use it itself.

Context in React is a feature that helps avoid such situations. It's a container for data and functions that specified components can access. You can store a component's state value and a function to update that state within the context.

To use context, you first need to define it:

const MyContext = createContext(defaultValue)

Then, at the top of the component tree, you render the Context Provider so that all components rendered within it have access to it. In the component where the context state is needed, you can either return the Context Consumer or use the useContext hook:

const ParentComponent = () => { const [parentState, setParentState] = useState(20); // pass desired values which will be held in context return <MyContext.Provider value={{ parentState, setParentState }}> <MidComponent /> </MyContext.Provider> } const MidComponent = () => { return <LowerComponent />; } const LowerComponent = ({ val }) => { return ( <MyContext.Consumer> {context => ( <div> Value is equal: {context.parentState}</div> )} </MyContext.Consumer> ); // or const context = useContext(MyContext); return <div> Value is equal: {context.parentState}</div>; }

Docs about context are available here.

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.