Preparing your workspace
Context provides a way to make data available to many components in a component tree without manually passing it through every level.
Context is useful for information that many components need, such as the current theme, authenticated user, locale, or application-level preferences. A context is created, a Provider supplies its value, and consumers can read the value using useContext. Context can simplify deeply nested prop passing, but it should not automatically be used for every piece of state. Frequent changes to a large context can cause many consumers to update, so context design should remain intentional.
An application can provide the current authenticated user through context so navigation, profile menus, and account pages can access it.
import { createContext, useContext } from 'react';
const ThemeContext = createContext('light');
function Button() {
const theme = useContext(ThemeContext);
return <button data-theme={theme}>Save</button>;
}
export default function App() {
return (
<ThemeContext.Provider value="dark">
<Button />
</ThemeContext.Provider>
);
}The Button component reads the shared theme value 'dark' without receiving it through props.