Skip to content

Latest commit

 

History

History
112 lines (79 loc) · 2.63 KB

File metadata and controls

112 lines (79 loc) · 2.63 KB
title createContext
order 5
use_cases prop drilling, global state, theme providers, user authentication, app-wide settings, dependency injection
tags
context
providers
global-state
props
dependency-injection
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

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>
	);
}

Related