Managing data between components is one of the most common challenges in React. When applications grow, passing data through multiple component levels using props becomes messy. This is where useContext helps.
πΉ What is useContext?
useContext is a React Hook that allows you to share data globally across components without prop drilling.
In simple words:
useContext lets components access shared data directly, no matter how deep they are in the component tree.
πΉ The Problem: Prop Drilling
If GrandChild needs data from App, you must pass props through every level, even if intermediate components donβt need it.
β This makes code:
Hard to maintain
Hard to read
Error-prone
πΉ Solution: React Context + useContext
Context provides a central store for shared data.
πΉ Steps to Use useContext
1οΈβ£ Create Context
import { createContext } from "react";
export const UserContext = createContext();
2οΈβ£ Provide Context Value
import { UserContext } from "./UserContext";
function App() {
return (
);
}
3οΈβ£ Consume Context using useContext
import { useContext } from "react";
import { UserContext } from "./UserContext";
function Dashboard() {
const user = useContext(UserContext);
return
Welcome {user.name}
;}
β No props
β Clean code
β Direct access to shared data
πΉ How useContext Works (Logic)
Context is created
Provider wraps components
Value is stored in Provider
Any child component can access it using useContext
When value changes β components re-render automatically
πΉ Real-World Use Cases
useContext is commonly used for:
Authentication (user details)
Theme (dark/light mode)
Language settings
Global app state
User roles (Admin / Student)
πΉ Example: Theme Context
const ThemeContext = createContext();
function App() {
return (
);
}
function Page() {
const theme = useContext(ThemeContext);
return
}
Top comments (0)