The useContext hook is a built-in hook in React that allows components to access the value of a context directly without the need for a Context.Consumer component. It provides a way to share data between components without passing props through every level of the component tree.
To use the useContext hook, you first need to create a context using the createContext function. This function returns an object with two properties: Provider and Consumer. The Provider component is used to wrap the parent component that will provide the context value, while the Consumer component is used to access the context value in child components.
Here’s an example of how to use the useContext hook:
// Create a context const MyContext = React.createContext(); // Create a parent component that provides the context value function ParentComponent() { const contextValue = "Hello from context"; return ( <MyContext.Provider value={contextValue}> <ChildComponent /> </MyContext.Provider> ); } // Create a child component that consumes the context value function ChildComponent() { const contextValue = React.useContext(MyContext); return <div>{contextValue}</div>; } // Render the parent component ReactDOM.render(<ParentComponent />, document.getElementById("root"));
In this example, the ParentComponent provides the context value “Hello from context” using the MyContext.Provider component. The ChildComponent then uses the useContext hook to access the context value directly without the need for a Context.Consumer component.
The output of this example will be a div element displaying “Hello from context”.