π React Global State using useContext β Share Data Across Components (2025 Guide)
π§² Introduction β Why Use Global State with useContext?
As your React.js application grows, managing state across multiple components becomes tricky. Prop drilling can make code messy and hard to maintain, especially when multiple layers are involved.
Thatβs where the useContext hook and Context API come in. They allow you to manage global stateβsuch as theme, user info, language settings, or authenticationβwithout prop drilling.
π― In this guide, youβll learn:
- How to create and use React Context with
useContext - Share state globally without third-party libraries
- Build custom providers and context hooks
- Best practices for scalable global state management
π What Is Global State?
Global state refers to any data that needs to be accessible across multiple unrelated componentsβsuch as user authentication status, UI themes, or shopping cart data.
βοΈ What Is useContext?
useContext is a built-in React Hook that lets you access the current value of a Context inside any functional component.
β Syntax:
const value = useContext(MyContext);
π You must use it within a <MyContext.Provider> or youβll get undefined.
π§± 1. Step-by-Step β Create Global State with useContext
β Step 1: Create Context
import { createContext } from 'react';
export const ThemeContext = createContext();
β Step 2: Build a Context Provider
import { useState } from 'react';
import { ThemeContext } from './ThemeContext';
export 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>
);
}
β Step 3: Wrap Your App
import { ThemeProvider } from './ThemeProvider';
function Root() {
return (
<ThemeProvider>
<App />
</ThemeProvider>
);
}
β Step 4: Consume Global State in Any Component
import { useContext } from 'react';
import { ThemeContext } from './ThemeContext';
function ThemeToggler() {
const { theme, toggleTheme } = useContext(ThemeContext);
return (
<button onClick={toggleTheme}>
Current Theme: {theme}
</button>
);
}
β
No prop drilling required
β
Works across component levels
π§ͺ 2. Custom Hook for Cleaner Context Access
You can abstract useContext into a custom hook:
import { useContext } from 'react';
import { ThemeContext } from './ThemeContext';
export function useTheme() {
return useContext(ThemeContext);
}
β Usage:
const { theme, toggleTheme } = useTheme();
π Promotes clean and consistent context usage
π§ 3. Real-World Use Cases
| Use Case | Data Stored |
|---|---|
| π Theme | light/dark, color settings |
| π Auth | user info, tokens, login/logout |
| π Cart | product list, total price |
| π Language | current locale, i18n switchers |
| βοΈ App Settings | UI toggles, preferences |
β οΈ 4. Limitations of useContext for Global State
| Limitation | Workaround |
|---|---|
| No built-in state updates | Combine with useState or useReducer |
| Rerenders all consuming components | Split context into smaller units |
| Poor for large-scale apps | Use Zustand, Redux, Jotai, or Recoil |
π Best Practices
β
Use context only for globally shared data
β
Split context domains (e.g., ThemeContext, AuthContext)
β
Wrap context usage in custom hooks
β
Keep context logic separate in provider components
β
Avoid frequent updates in context (move to local state or memoize)
π Summary β Recap & Next Steps
Reactβs useContext and Context API make it easy to manage shared application state without third-party libraries. For simple global data like themes, user info, and language, this is an ideal built-in solution.
π Key Takeaways:
- Use
createContextto define shared global state - Wrap components in a
<Provider>to supply values - Access values via
useContext()inside any functional component - Combine with
useStateoruseReducerto handle updates - Use custom hooks to abstract and simplify usage
βοΈ Real-World Relevance:
Used in apps like Netflix, Facebook, and Shopify for themes, user sessions, and application-wide configurations.
β FAQ Section
β Whatβs the difference between useContext and Redux?
β
useContext is built-in and ideal for small-scale global state. Redux offers more structure and is better for complex, async-heavy apps.
β Can I use useContext without a provider?
β No. Youβll get undefined if you try to use useContext without wrapping the tree in its corresponding <Provider>.
β Does using context trigger re-renders?
β
Yes. Any component using useContext will re-render when the context value changes.
β Can I have multiple contexts in one app?
β
Yes! You can define and combine multiple contexts (e.g., Auth, Theme, Locale) without conflict.
β Should I use useContext or useState?
β
Use useState for local state, and useContext when multiple components need access to the same data.
Share Now :
