- Home
- /
- Tutorials
- /
- React Tutorial
- /
- Context Patterns
Context
Context Patterns
Exporting the raw context object makes every consumer repeat the same three lines. Wrapping it in a provider component and a hook is the pattern almost every codebase converges on.
Provider plus hook
Two exports - a provider component that owns the state, and a hook that reads it and throws a useful error when used outside. Consumers never touch createContext or useContext directly.
The standard shape
jsx
const ThemeContext = React.createContext(null)
// 1. The provider owns the state.
function ThemeProvider({ children }) {
const [theme, setTheme] = React.useState("light")
const toggle = () => setTheme((t) => (t === "light" ? "dark" : "light"))
return (
<ThemeContext.Provider value={{ theme, toggle }}>
{children}
</ThemeContext.Provider>
)
}
// 2. The hook hides useContext and fails loudly if misused.
function useTheme() {
const value = React.useContext(ThemeContext)
if (value === null) throw new Error("useTheme must be used inside a ThemeProvider")
return value
}
function Toolbar() {
const { theme, toggle } = useTheme()
return <button onClick={toggle}>Theme: {theme} (click to change)</button>
}
function App() {
return (
<ThemeProvider>
<Toolbar />
</ThemeProvider>
)
}
const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(<App />)