[]previous and next page

createContext

Creates a context: a value that components read with useContext without passing it through props.

Creates a context: a value that components read with useContext without passing it through props. Render the returned component around a subtree to provide a value. The value is read once; pass a signal accessor or a store to provide something reactive. On the server the provider builds its subtree once.

Import#

ts
import { createContext } from "@shadow-js/core";

Signature#

ts
function createContext<T>(defaultValue?: T, options?: ContextOptions): Context<T>

Parameters#

Name Description
defaultValue Returned by useContext when no provider is above the reader. Undefined (or omitted) means the context has no default, so reading it without a provider throws.
options A diagnostics name. Undefined uses the default.

Returns#

The context, which is also its provider component.

Examples#

ts
import { createContext, useContext } from "@shadow-js/core";

const Theme = createContext<"light" | "dark">("light", { name: "Theme" });

function Label() {
  return <p>Theme: {useContext(Theme)}</p>;
}

const app = <Theme.Provider value="dark"><Label /></Theme.Provider>;