useContext
Reads and subscribes to a React context value.
Syntax
const value = useContext(SomeContext) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
SomeContext | Context | Yes | The context object created with createContext. |
Returns
any — The context value from the nearest matching provider above.
Examples
const ThemeContext = createContext('light');
function Button() {
const theme = useContext(ThemeContext);
return <button className={theme}>Click</button>;
}
<ThemeContext.Provider value="dark">
<Button />
</ThemeContext.Provider>
Notes
Returns the value of the closest matching provider, or the default passed to
createContext when no provider is found. The component re-renders whenever the
provider value changes. Pass the context object itself, not Context.Provider
or Context.Consumer.