DEV Community

JulianneHuynh
JulianneHuynh

Posted on

useContext in React JS

Normally, you would manually pass state down as a prop from a parent component to each child component. However, passing the prop down would become tedious if the child component had nested components. To solve this issue, you can use the useContext hook in React, which provides state from a parent component to the child component, no matter how deeply nested it may be. To use useContext, you first create a context object using the createContext function, where the initial value is used as an argument. The context object has two parts: the provider, which wraps around the code that requires access to that information in the context, and a value set to the context used. In the child component, you can import the value prop using value = useContext(xContext). All components wrapped within the provider will have access to the value prop.

Top comments (0)