Sub topic 5
Reading context with useContext
This chapter assumes you know JSX and props, the useState hook, and how createContext and Provider work from the previous chapters. Here the focus is the reading side: how a component gets a value out of context and what can go wrong.
What useContext does
useContext(SomeContext) is a hook that returns the current value of a context. React decides that value by looking up the component tree from the calling component and picking the closest matching Provider. If no Provider is found, the hook returns the default value passed to createContext.
The argument is the context object itself, the thing createContext returned. It is not the Provider and not a value.
A working example
import { createContext, useContext, useState } from 'react';
const ThemeContext = createContext('light');
function App() {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={theme}>
<Toolbar />
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle theme
</button>
</ThemeContext.Provider>
);
}
function Toolbar() {
return <ThemedButton />;
}
function ThemedButton() {
const theme = useContext(ThemeContext);
return <button className={`btn-${theme}`}>Save</button>;
}Toolbar receives no props and knows nothing about the theme. ThemedButton reads it directly. When App calls setTheme, the Provider receives a new value, and React re-renders every component below it that called useContext(ThemeContext).
How the value is resolved
Three details follow from this lookup:
- Only Providers above the component count. A Provider rendered by the same component, or placed below it, is invisible to that component's own
useContextcall. - Only the same context object matches. Two contexts created by two separate
createContextcalls are unrelated, even if their default values are identical. - Only the nearest Provider counts. An outer Provider's value is ignored for components inside an inner one.
Rules for calling it
useContext follows the normal rules of hooks. Call it at the top level of a function component or a custom hook, not inside loops, conditions, or event handlers. If you need the value in a handler, read it at the top of the component and use the variable inside the handler.
Common errors
- Passing the wrong thing.
useContext(ThemeContext.Provider)oruseContext(theme)does not work. Pass the context object:useContext(ThemeContext). - Reading from the same component that provides. If
Apprenders the Provider and also callsuseContext(ThemeContext),Appgets the default value, because no Provider is above it. - Omitting the
valueprop.<ThemeContext.Provider>withoutvaluesuppliesundefined. It does not fall back to the default value. - Destructuring a default of
null. If the context was created withcreateContext(null), thenconst { user } = useContext(AuthContext)throws aTypeErrorwhenever there is no Provider above the component. - Expecting partial subscriptions. A component that calls
useContextre-renders whenever the context value changes, even if it uses only one field of that value. The next chapters cover how to manage this.
Reading context in practice
Calling useContext(ThemeContext) directly in every component works, but it spreads knowledge of the context object across your codebase. A later chapter shows how to hide it behind a custom hook such as useTheme(). For now, the key skill is predicting what a given component will see: find the nearest matching Provider above it, read its value, and fall back to the default if none exists.
Exercise
In the example above, ThemedButton is moved so that App renders it directly inside App's own return, outside the ThemeContext.Provider. The state is 'dark'. What class name does the button get, and why?
Show answer
It gets btn-light. There is no ThemeContext Provider above that button, so useContext(ThemeContext) returns the default value 'light' passed to createContext, regardless of the theme state in App.