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)