React Context and the Provider Pattern
Context lets a component pass a value to any descendant without threading props through every level. The Provider pattern wraps that mechanism in a reusable component plus a custom hook. React Context is documented in createContext and useContext.
1. The three pieces
const ThemeContext = createContext('light'); // 1. create (with a default)
<ThemeContext.Provider value="dark"> // 2. provide
<App />
</ThemeContext.Provider>
const theme = useContext(ThemeContext); // 3. consume
useContext returns the value from the nearest Provider above the component. With no Provider above it, it returns the default passed to createContext.
2. What React Context Is (and Isn’t)
- It is a dependency injection mechanism, not a state manager. The state still lives in some component (usually the Provider) via
useStateoruseReducer. - It solves prop drilling for values many components need: theme, locale, current user, a service client.
3. A production-style provider
const AuthContext = createContext(null);
export function AuthProvider({ children }) {
const [user, setUser] = useState(null);
... premium content.