Using useContext for Global State
Learn how to share state across components using React Context API and useContext hook. Master context API to avoid prop drilling and manage global state efficiently.

What is useContext?#
useContext is a React hook that allows you to consume context values in functional components. It provides a way to share data across the component tree without prop drilling. Context is designed to share data that can be considered "global" for a tree of React components, such as the current authenticated user, theme, or preferred language.
Before the Context API, passing data through multiple levels of components required "prop drilling" - passing props through intermediate components that don't need them. useContext solves this problem by allowing you to access context values directly in any component within the provider tree.
Installation and Setup#
useContext is part of React core, so no additional installation is needed. If you're using React 16.8 or later, you already have access to useContext. To verify your React version:
npm list reactIf you need to upgrade React:
npm install react@latest react-dom@latestCreating Context#
The first step is to create a context using createContext. This creates a context object that components can subscribe to:
import { createContext } from 'react';
const ThemeContext = createContext('light');
export default ThemeContext;The default value ('light' in this example) is used when a component consumes the context outside of a Provider. It's a fallback value that helps with testing and provides a sensible default.
Providing Context#
To make context values available to components, wrap your component tree with a Context.Provider. The Provider accepts a value prop that will be available to all consuming components:
import { useState } from 'react';
import ThemeContext from './ThemeContext';
function App() {
const [theme, setTheme] = useState('dark');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
<Toolbar />
<Content />
<Footer />
</ThemeContext.Provider>
);
}Any component inside the Provider can access the theme and setTheme values. The value prop can be any JavaScript value - strings, numbers, objects, arrays, or even functions.
Consuming Context#
To consume context values, use the useContext hook. It takes the context object as an argument and returns the current context value:
import { useContext } from 'react';
import ThemeContext from './ThemeContext';
function Button() {
const { theme, setTheme } = useContext(ThemeContext);
const toggleTheme = () => {
setTheme(theme === 'light' ? 'dark' : 'light');
};
return (
<button
onClick={toggleTheme}
className={`btn btn-${theme}`}
>
Current theme: {theme}
</button>
);
}Complete Example: Theme Switcher#
Let's build a complete theme switcher application:
// ThemeContext.js
import { createContext, useState } from 'react';
export const ThemeContext = createContext();
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
const toggleTheme = () => {
setTheme(prevTheme => prevTheme === 'light' ? 'dark' : 'light');
};
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
}
// App.js
import { ThemeProvider } from './ThemeContext';
import Header from './Header';
import MainContent from './MainContent';
function App() {
return (
<ThemeProvider>
<Header />
<MainContent />
</ThemeProvider>
);
}
// Header.js
import { useContext } from 'react';
import { ThemeContext } from './ThemeContext';
function Header() {
const { theme, toggleTheme } = useContext(ThemeContext);
return (
<header className={`header-${theme}`}>
<h1>My App</h1>
<button onClick={toggleTheme}>
Switch to {theme === 'light' ? 'dark' : 'light'} mode
</button>
</header>
);
}Multiple Contexts#
You can use multiple contexts in your application. Each context should represent a different concern:
// UserContext.js
export const UserContext = createContext();
// LanguageContext.js
export const LanguageContext = createContext();
// App.js
function App() {
return (
<UserContext.Provider value={user}>
<LanguageContext.Provider value={language}>
<Application />
</LanguageContext.Provider>
</UserContext.Provider>
);
}
// Component using multiple contexts
function Component() {
const user = useContext(UserContext);
const language = useContext(LanguageContext);
return <div>{user.name} - {language}</div>;
}Performance Considerations#
Context can cause performance issues if not used carefully. Every time the context value changes, all consuming components re-render. To optimize:
- Split contexts by concern (don't put everything in one context)
- Memoize context values when possible
- Use useMemo for expensive context values
- Consider using multiple smaller contexts instead of one large context
// Optimized context with useMemo
function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
const value = useMemo(() => ({
theme,
toggleTheme: () => setTheme(prev => prev === 'light' ? 'dark' : 'light')
}), [theme]);
return (
<ThemeContext.Provider value={value}>
{children}
</ThemeContext.Provider>
);
}Best Practices#
- Create separate contexts for different concerns - Don't put unrelated data in the same context
- Use context for truly global state - Not for data that's only needed by a few components
- Consider performance implications - Context updates trigger re-renders in all consumers
- Combine with useReducer for complex state - For state with complex update logic
- Provide default values - Helps with testing and provides fallbacks
- Create custom hooks - Wrap useContext calls in custom hooks for better API
Custom Hook Pattern#
Create a custom hook to encapsulate context consumption:
// useTheme.js
import { useContext } from 'react';
import { ThemeContext } from './ThemeContext';
export function useTheme() {
const context = useContext(ThemeContext);
if (!context) {
throw new Error('useTheme must be used within ThemeProvider');
}
return context;
}
// Usage
function Component() {
const { theme, toggleTheme } = useTheme();
// ...
}Common Use Cases#
- Theming - Dark/light mode, color schemes
- Authentication - Current user, login status
- Localization - Current language, translations
- Feature flags - Enable/disable features
- UI state - Modals, sidebars, notifications
useContext is a powerful tool for managing global state in React applications. When used correctly, it eliminates prop drilling and makes your code cleaner and more maintainable. Remember to use it judiciously - not all state needs to be global, and overusing context can lead to performance issues.