requireContext()function
requireContext(context: Context<T | null>, caller?: AnyCaller): T
requireContext(context: Context<T | undefined>, caller?: AnyCaller): T
requireContext(context: Context<T>, caller?: AnyCaller): T
| Param | Type | |
|---|---|---|
context | Context<Tnull> | The React Context to read the current value of. required |
caller | AnyCaller | Function to attribute the thrown RequiredError to (defaults to requireContext). |
context | Context<Tundefined> | required |
caller | AnyCaller | Any calling function or constructor, usually referring to something that can call in the current scope that can appear in a stack trace. |
context | Context<T> | required |
| Return | |
|---|---|
T | The current context value, guaranteed non-nullish. |
T |
| Throws | |
|---|---|
unknown | RequiredError If the context value is null or undefined (i.e. used outside its provider). |
Use the value of a React Context, or throw RequiredError if the context was unset.
- Reads the context with React's
use(), so it must be called inside a component or hook. - Treats both
nullandundefinedas "unset" and throws, naming the context'sdisplayNamein the message.
Reads a React context and throws RequiredError if the value is null or undefined. Use it instead of use(context) when a context must be provided by an ancestor — every require*() hook in the library follows this pattern.
Things to know:
- Reads the context with React's
use(), so it must be called inside a component or hook. - Treats both
nullandundefinedas "unset" and throws, naming the context'sdisplayNamein the message. - Pass the calling function as
callerso the thrownRequiredErroris attributed to it (defaults torequireContextitself).
Usage
import { requireContext } from "shelving/ui";
function requireNavigation(): NavigationStore {
return requireContext(NavigationContext, requireNavigation);
}Examples
const theme = requireContext(ThemeContext);