Sub topic 1
React useContext: Sharing State Across Components Without Prop Drilling
Prerequisites
This chapter assumes JavaScript ES6 modules, React function components, JSX, props, and basic component re-rendering. You should also know the useState hook.
The problem: passing props through many layers
Props are values a parent gives to a child. They work well when the receiving component is close to the source. They become awkward when a deeply nested component needs a value.
Suppose App owns a theme, but ThemedButton needs it:
function App() {
const theme = 'dark';
return <Toolbar theme={theme} />;
}
function Toolbar({ theme }) {
return <Panel theme={theme} />;
}
function Panel({ theme }) {
return <ThemedButton theme={theme} />;
}
function ThemedButton({ theme }) {
return <button className={`btn-${theme}`}>Save</button>;
}Toolbar and Panel do not use theme; they only pass it along. This is called prop drilling. React context provides another path for values through a component subtree.
Creating a context
createContext creates a context object. A context is a named channel for a value.
import { createContext, useContext } from 'react';
const ThemeContext = createContext('light');
function ThemedButton() {
const theme = useContext(ThemeContext);
return <button className={`btn-${theme}`}>Save</button>;
}useContext reads the value from the nearest matching provider above the component. The button does not need a theme prop.
Providing a value to a subtree
A provider supplies a value to every descendant that reads the same context:
function App() {
const theme = 'dark';
return (
<ThemeContext.Provider value={theme}>
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar() {
return <ThemedButton />;
}Toolbar passes no theme. ThemedButton still receives "dark" through context. The provider affects only its children, so separate parts of an application can use different providers.
What the default value is for
The argument to createContext is used when a component has no matching provider above it:
const ThemeContext = createContext('light');If ThemedButton renders outside ThemeContext.Provider, it reads "light". This default is a fallback, not automatically shared state. It also does not replace a provider’s value.
Exercise
If a button is inside a provider with value="dark", but the context default is "light", which value does useContext return?
Show answer
It returns "dark", because the nearest provider overrides the default.