| title | createContext | |||||
|---|---|---|---|---|---|---|
| order | 5 | |||||
| use_cases | prop drilling, global state, theme providers, user authentication, app-wide settings, dependency injection | |||||
| tags |
|
|||||
| version | 1.0 | |||||
| description | Create a context object with a `Provider` component and a default value. |
createContext creates a context object.
The returned object contains a Provider component and an optional defaultValue; useContext reads the nearest matching provider value.
import { createContext } from "solid-js";interface Context<T> {
id: symbol;
Provider: (props: { value: T; children: any }) => any;
defaultValue: T;
}
function createContext<T>(
defaultValue?: undefined,
options?: { name?: string }
): Context<T | undefined>;
function createContext<T>(
defaultValue: T,
options?: { name?: string }
): Context<T>;- Type:
T
Default value returned by useContext when no matching provider is found.
- Type:
string
Debug name used by development tooling.
- Type:
Context<T>orContext<T | undefined>
Returns a context object containing id, Provider, and defaultValue.
Context.Providerpasses itsvalueprop to descendant calls touseContext.useContextreads the nearest matching provider in the current owner tree.- If no matching provider is found,
useContextreturnsdefaultValuewhen one was supplied, orundefinedotherwise.
- During Hot Module Replacement (HMR), recreating a context in a reloaded module creates a new context object.
- If provider and consumer modules are temporarily out of sync during reload,
useContextcan read a different context object and return the default value orundefined. - Defining the context in its own module keeps the exported context object stable across imports.
import { createContext } from "solid-js";
type Theme = "light" | "dark";
const ThemeContext = createContext<Theme>("light");import { createContext } from "solid-js";
const CounterContext = createContext<{ count: number }>();
function CounterProvider(props) {
return (
<CounterContext.Provider value={{ count: 1 }}>
{props.children}
</CounterContext.Provider>
);
}