useContext
Reads the current value of a context.
- For
createContext<T>()(default-less): returns the value from the nearest enclosing Provider, or throwsContextNotFoundErrorif none is mounted. Return type isT(no narrowing required). - For
createContext<T>(defaultValue): returns the value from the nearest enclosing Provider, ordefaultValueif none is mounted.
In Solid, useContext is the canonical way to read context. There is no
need for a wrapper hook that throws on missing Provider — the default-less
form already does that, and its return type is T.
Import
import { useContext } from "solid-js";Type signature
function useContext<T>(context: Context<T>): T;Parameters
context
A context returned from createContext
Return value
The value provided by the nearest enclosing Provider, or the
default if one was supplied to createContext
Examples
const TodosContext = createContext<TodosCtx>();
function TodoList() { const [todos, { addTodo }] = useContext(TodosContext); // throws if no Provider // ...}Related types
ContextNotFoundError
class ContextNotFoundError extends Error { constructor() { super( __DEV__ ? "Context must either be created with a default value or a value must be provided before accessing it." : "" ); }}