Providers as components
A provider component that owns its state and exposes a hook is the usual shape (CounterProvider and CartProvider above).
A provider component that owns its state and exposes a hook is the usual shape (CounterProvider and CartProvider above). A context with no default already fails with CONTEXT_MISSING when the provider is absent. If you prefer your own message, give the context a null default and check for it in the hook:
src/strict-context.tsxtsx
import { createContext, useContext } from "@shadow-js/core";
const SessionContext = createContext<{ user: string } | null>(null);
export function useSession(): { user: string } {
const session = useContext(SessionContext);
if (session === null) throw new Error("useSession() needs a SessionContext provider above it");
return session;
}
function Who() {
return <p>{useSession().user}</p>;
}
export function Safe() {
return (
<SessionContext.Provider value={{ user: "ok" }}>
<Who />
</SessionContext.Provider>
);
}