Share state across the component tree without prop drilling using useContext.
Context lets you pass data through the component tree without manually threading props at every level.
import { createContext, useContext } from 'react'
type Theme = 'light' | 'dark'
const ThemeContext = createContext<Theme>('light')
Wrap the part of the tree that needs the value:
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar() {
const theme = useContext(ThemeContext);
return <div className={theme}>I am {theme}</div>;
}
Use context for values that many components at different nesting levels need: theme, locale, current user, auth status. Avoid it for state that only a few nearby components need — props work better there.
Create a UserContext with the value type { name: string }.
In App:
{ name: 'Alice' } via UserContext.ProviderWelcome component, consume the context and render <p>Welcome, {name}!</p>export default function App(): JSX.Element { return <h1>Hello world</h1> }
No test results yet
Click Run Tests or press Ctrl+Enter