React question detail
What is useContext? What are the steps to follow for useContext?
The useContext hook is a built-in React Hook that lets you access the value of a context inside a functional component without needing to wrap it in a <Context.Consumer> component.
It helps you avoid prop drilling (passing props through multiple levels) by allowing components to access shared data like themes, authentication status, or user preferences.
The usage of useContext involves three main steps:
Step 1 : Create the Context
Use React.createContext() to create a context object.
import React, { createContext } from 'react';
const ThemeContext = createContext(); // default value optional
You typically export this so other components can import it.
Step 2: Provide the Context Value
Wrap your component tree (or a part of it) with the Context.Provider and pass a value prop.
function App() {
return (
<ThemeContext.Provider value="dark">
<MyComponent />
</ThemeContext.Provider>
);
}
Now any component inside <ThemeContext.Provider> can access the context value.
Step 3: Consume the Context with **useContext**
In any functional component inside the Provider, use the useContext hook:
import { useContext } from 'react';
function MyComponent() {
const theme = useContext(ThemeContext); // theme = "dark"
return <p>Current Theme: {theme}</p>;
}