Sub topic 2
Reading Context with `useContext`
Assume you know JavaScript modules, JSX, function components, props, useState, and basic React re-rendering. React context lets a component read a value from the nearest matching provider without receiving that value through every intermediate component.
Reading context with `useContext`
Create a context with createContext, then read it with useContext:
import { createContext, useContext, useState } from 'react';
const ThemeContext = createContext('light');
export default 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 does not need a theme prop. ThemedButton reads the value directly from the nearest ThemeContext.Provider.
The argument to createContext is the default value. React uses it only when no matching provider exists above the component. It is useful for simple fallbacks and tests, but it does not update application state.
Nested providers override values
A provider affects its descendants. A nested provider can replace the value for only its own subtree.
This makes context useful for local overrides, such as a dark dialog inside a light page. A consumer always reads the closest provider, not a merged value from all providers.
Sharing changing state through context
Put state in the provider and pass both the state and its updater when consumers need to change it:
const value = { theme, setTheme };
<ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>Consumers can then call setTheme. Keep the provider near the components that need the shared state.
How context updates cause re-renders
When the provider’s value changes, components that read that context with useContext render again. React compares the old and new values with Object.is. A newly created object is therefore different on every render:
<ThemeContext.Provider value={{ theme, setTheme }}>Use useMemo for object values when provider re-renders are frequent. Also remember that memo does not prevent a component from re-rendering when its consumed context changes.
Exercise
A component reads ThemeContext, but no provider is above it. Which value does it receive?
Show answer
It receives the default value passed to createContext, such as 'light'.