How to use useContext for global state in React
· Category: React
Short answer
React Context provides a way to pass data through the component tree without manually threading props. useContext reads the value from a context directly in a functional component.
Steps
- Create a context with
React.createContext(defaultValue). - Wrap your tree in the context's
Providerand pass a value. - In any child component, call
useContext(MyContext)to access the value.
Example
import { createContext, useContext, useState } from 'react';
const ThemeContext = createContext('light');
function App() {
const [theme, setTheme] = useState('dark');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar() {
const { theme, setTheme } = useContext(ThemeContext);
return (
<button onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}>
Toggle {theme}
</button>
);
}
Tips
- Context is not a state manager; it is a transport mechanism. Pair it with
useStateoruseReducer. - Split contexts by domain to avoid unnecessary re-renders.
- For high-frequency updates, consider a dedicated state library like Zustand or Jotai.