What is useContext and when should you avoid it?
Hint
Subscribe to context value — every consumer re-renders when context value changes
Full Answer
// 1. Create context
const ThemeContext = createContext('light');
// 2. Provide value
function App() {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
<Page />
</ThemeContext.Provider>
);
}
// 3. Consume anywhere in the tree
function Button() {
const { theme, setTheme } = useContext(ThemeContext);
return <button className={theme}>Click</button>;
}
When to avoid:
- High-frequency updates — every consumer re-renders on every context change. Putting frequently-changing state (mouse position, scroll) in context is expensive.
- Unrelated values in one context — split into separate contexts so consumers only re-render for changes they care about.
// ❌ One fat context — Button re-renders when user changes even if only needs theme
const AppContext = createContext({ theme, user, cart });
// ✅ Split contexts — each consumer only subscribes to what it needs
const ThemeContext = createContext(theme);
const UserContext = createContext(user);
💡 Context is not a replacement for state management — it's a way to avoid prop drilling. For high-frequency global state, use Zustand or Jotai which use subscription-based updates.
More Hooks Questions
Practice this in a timed sprint
5 free questions, no signup required