useContext
Reads the nearest provided value of context.
Reads the nearest provided value of context. Falls back to its default; throws when there is
neither a provider nor a default, because no correct value exists. The lookup follows the current
owner, so call it while a component runs (or in an effect or memo it creates), not after an
await or in an event handler. The read is not tracked.
Import#
ts
import { useContext } from "@shadow-js/core";
Signature#
ts
function useContext<T>(context: Context<T>): T
Parameters#
| Name | Description |
|---|---|
context |
A context made by createContext. |
Returns#
The value of the nearest provider above the current owner, else the default value.
Throws#
- ShadowError
CONTEXT_MISSINGwhen no provider is above the current owner and the context's default isundefined.
Examples#
ts
import { createContext, useContext } from "@shadow-js/core";
const User = createContext<{ name: string }>();
function Greeting() {
const user = useContext(User); // throws CONTEXT_MISSING without a provider
return <p>Hello, {user.name}</p>;
}