DEV Community

PONVEL M
PONVEL M

Posted on

Understanding useContext in React (With Simple Examples)

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

Hello;

}

Top comments (0)