createContext
Edit this pagecreateContext creates a context object.
The returned object contains a Provider component and an optional defaultValue; useContext reads the nearest matching provider value.
Import
import { createContext } from "solid-js";Type
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>;Parameters
defaultValue
- Type:
T
Default value returned by useContext when no matching provider is found.
options
name
- Type:
string
Debug name used by development tooling.
Return value
- Type:
Context<T>orContext<T | undefined>
Returns a context object containing id, Provider, and defaultValue.
Behavior
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.
Notes
- 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.
Examples
Create a context with a default value
import { createContext } from "solid-js";
type Theme = "light" | "dark";
const ThemeContext = createContext<Theme>("light");Create a provider
import { createContext } from "solid-js";
const CounterContext = createContext<{ count: number }>();
function CounterProvider(props) { return ( <CounterContext.Provider value={{ count: 1 }}> {props.children} </CounterContext.Provider> );}