What is usecontext?
The useContext Hook is used to access data from a React Context without passing props manually through multiple levels of components.
It helps solve the problem of prop drilling, where data needs to be passed from a parent component to deeply nested child components through intermediate components.
Why use useContext?
Imagine an application where user information, theme settings, or language preferences are needed by many components.
Without useContext, you would pass these values through props at every level.
With useContext, any component can directly access the shared data from the Context.
Syntax:
import { useContext } from "react";
const value = useContext(MyContext);
Steps to Use useContext
1. Create a Context
import { createContext } from "react";
const UserContext = createContext();
2. Provide the Context Value
import { UserContext } from "./UserContext";
function App() {
return (
<UserContext.Provider value="Raksha">
<Dashboard />
</UserContext.Provider>
);
}
3. Consume the Context Using useContext
import { useContext } from "react";
import { UserContext } from "./UserContext";
function Profile() {
const user = useContext(UserContext);
return <h1>Welcome, {user}</h1>;
}
How It Works
- createContext() creates a Context object.
- The Provider component shares data with its child components.
- useContext() reads the value from the nearest Provider.
- Any component inside the Provider can access the shared data directly.
Real-World Use Cases
- User authentication information
- Theme switching (Dark Mode / Light Mode)
- Language settings
- Shopping cart data
- Application-wide settings
Top comments (0)