React's useContext hook is primarily used to access shared values via context, eliminating the need to explicitly pass props through the component tree. To pass multiple values, package them into an object and pass this object as the value prop of the Context Provider. Here's an example of how to implement it:
First, create a Context:
jsximport React, { createContext } from 'react'; // Create a Context object const MyContext = createContext();
Second, wrap your child components with the MyContext.Provider component and pass an object as the value prop, which contains multiple values:
jsxfunction App() { // Create an object containing multiple values const contextValue = { user: { name: 'Alice', age: 25 }, theme: 'dark', language: 'en' }; return ( <MyContext.Provider value={contextValue}> {/* ...your component structure */} </MyContext.Provider> ); }
Finally, in child components that need to access these values, use the useContext hook to retrieve them:
jsximport React, { useContext } from 'react'; function MyComponent() { // Access the context values using the useContext hook const { user, theme, language } = useContext(MyContext); return ( <div> <p>User: {user.name}</p> <p>Theme: {theme}</p> <p>Language: {language}</p> </div> ); }
In this example, we create a contextValue object containing multiple values such as user information, theme, and language, and pass it to MyContext.Provider. Within the MyComponent component, we access these values using the useContext hook and destructure them into individual variables. Now, within the MyComponent component, you can directly use variables like user, theme, and language without having to pass them through props from the parent component.