Component APIs

createContext

Edit this page

createContext 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> or Context<T | undefined>

Returns a context object containing id, Provider, and defaultValue.


Behavior

  • Context.Provider passes its value prop to descendant calls to useContext.
  • useContext reads the nearest matching provider in the current owner tree.
  • If no matching provider is found, useContext returns defaultValue when one was supplied, or undefined otherwise.

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, useContext can read a different context object and return the default value or undefined.
  • 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>
);
}

Report an issue with this page