React useContext Hook
25 April 2025 | Category: React Js
React apps often need to share data (like user info or theme settings) across many components. Passing props down manually from parent to child repeatedly can become messy. That’s where useContext
comes in.
Let’s break it all down step-by-step. 👇
🧠 What is useContext
?
useContext
is a React Hook that lets you access values from a Context directly in your component without passing props manually.
It works with the React Context API, which is designed to share global data (like authentication, theme, or language settings) across your app.
🤔 What is Context?
Context provides a way to pass data through the component tree without having to pass props at every level.
Think of it as a global storage for your app.
📘 When to Use useContext
- When many components need access to the same data
- When you want to avoid “prop drilling” (passing props through multiple levels)
🧪 Basic Example – Theme Context
1️⃣ Create the Context
import React, { createContext } from 'react';
export const ThemeContext = createContext();
This creates a context object.
2️⃣ Create a Provider Component
This component will wrap your app and provide the shared data.
import React, { useState } from 'react';
import { ThemeContext } from './ThemeContext';
function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
const toggleTheme = () => {
setTheme(prev => (prev === 'light' ? 'dark' : 'light'));
};
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
}
export default ThemeProvider;
Here, we use ThemeContext.Provider
to share theme
and toggleTheme
with any component inside it.
3️⃣ Use useContext
to Consume the Data
Now let’s use the context inside a component:
import React, { useContext } from 'react';
import { ThemeContext } from './ThemeContext';
function Header() {
const { theme, toggleTheme } = useContext(ThemeContext);
return (
<header style={{ background: theme === 'light' ? '#fff' : '#333', color: theme === 'light' ? '#000' : '#fff' }}>
<h1>Theme is {theme}</h1>
<button onClick={toggleTheme}>Toggle Theme</button>
</header>
);
}
export default Header;
Now the Header
can access and update the theme without any prop drilling.
4️⃣ Wrap Your App with the Provider
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import ThemeProvider from './ThemeProvider';
ReactDOM.render(
<ThemeProvider>
<App />
</ThemeProvider>,
document.getElementById('root')
);
🧵 Another Example – User Auth Context
Let’s say you want to share user login status across multiple pages.
Create the context:
export const AuthContext = createContext();
AuthProvider:
function AuthProvider({ children }) {
const [user, setUser] = useState(null);
const login = (userData) => setUser(userData);
const logout = () => setUser(null);
return (
<AuthContext.Provider value={{ user, login, logout }}>
{children}
</AuthContext.Provider>
);
}
Consume it anywhere:
import { useContext } from 'react';
import { AuthContext } from './AuthContext';
function Profile() {
const { user, logout } = useContext(AuthContext);
return user ? (
<div>
<p>Welcome, {user.name}!</p>
<button onClick={logout}>Log out</button>
</div>
) : (
<p>You are not logged in.</p>
);
}
📋 Benefits of useContext
✅ No more prop drilling
✅ Cleaner code
✅ Centralized state management
✅ Easy to share data across many components
⚠️ Things to Remember
❌ Don’t use useContext
alone without wrapping your components in a provider.
❌ Avoid storing large or constantly changing data in context (better to use Redux or Zustand).
✅ Use useContext
for theme, language, user info, settings, etc.
🔁 useContext vs Props
Feature | Props | useContext |
---|---|---|
Scope | Local to each component | Global (shared across components) |
Flexibility | Must pass manually | Direct access with useContext |
Simplicity | Simple for few levels | Easier for deep trees |
🎯 Summary
useContext
is used to access shared state from a Context.- Context is created with
createContext()
. - Data is passed using a
Provider
. - Any component inside that provider can use the shared data with
useContext
.
💡 Project Ideas to Practice
- Theme Switcher App (Dark/Light mode)
- Language Switcher (English, Hindi, etc.)
- Login System (Show different UI for logged-in users)