What is useContext?
useContext is a React hook that lets you access values from a Context directly, without prop drilling.
It works with the Context API, which is React’s built-in way to share data across components without passing props manually.
How it Works
Create a Context
import React, { createContext } from "react";
const UserContext = createContext();
This creates a "box" to store shared data.
Provide the Context Value
function App() {
return (
<UserContext.Provider value="Saran">
<Dashboard />
</UserContext.Provider>
);
}
Provider makes the value ("Saran") available to all child components.
Consume the Context with useContext
Why Use useContext?
Avoids Prop Drilling: No more passing props through multiple layers.
Cleaner Code: Components only use what they need.
Centralized State: Useful for themes, authentication, language settings, etc.
import React, { useContext } from "react";
function Profile() {
const user = useContext(UserContext);
return <p>Hello, {user}!</p>;
}
Top comments (0)