Skip to content

ContextNew in 7.2

Make a value available to everything a component renders, scoped to that component.

docs/learn/context.md
moduleXote.Contextboundarysrc/Context.resientryxote · xote/contextversion7.2.0
Raw Markdown

Context lets a component make a value available to everything it renders, without passing it through every component in between.

Info: A provided value is scoped to the component that provides it. Siblings, parents and everything rendered outside it never see it.

When to use context

Signals don't need a component to own them. A signal declared at module level is already shared state that any component can import:

1let session = Signal.make(None)

For a value the whole app shares in the browser, that's the simplest option. Reach for context when a global isn't enough:

  • Per-instance state. Two Tabs on a page each need their own selected tab, shared with their own Tab children. A module-level signal can only hold one.
  • Children you don't write. A component that receives children from its caller can't close over a local variable for them. Context reaches them without adding props at every call site.
  • Server rendering. Module-level state lives as long as the server process, so one request can see another request's values unless every global is reset. A provided value only exists for the render that provided it.
  • Tests. Each test can mount its own provider instead of mutating and resetting a global.

Declare a context

Declare a context once, with the default value a component gets when nothing above it provides one:

1let theme = Context.make("light")

Provide a value

Wrap a subtree in Context.Provider:

1<Context.Provider context=theme value="dark">
2 <Toolbar />
3</Context.Provider>

A component can also provide a value for everything it renders by calling Context.provide in its body. Each instance of the component then gets its own value:

1let selection = Context.make(Signal.make(0))
2
3module Tabs = {
4 @xote.component
5 let make = (~children: View.node) => {
6 Context.provide(selection, Signal.make(0))
7 <div class="tabs"> {children} </div>
8 }
9}

Context.provide raises if you call it outside a component body, because there's no render to scope the value to.

Read a value

Read the nearest provided value with Context.use:

1module Tab = {
2 @xote.component
3 let make = (~index: int, ~label: string) => {
4 let selected = Context.use(selection)
5 <button
6 class={Signal.get(selected) == index ? "tab active" : "tab"}
7 onClick={_ => Signal.set(selected, index)}>
8 {label}
9 </button>
10 }
11}

With no provider above, use returns the default passed to Context.make.

Share a value that changes

Providing a value doesn't make it reactive: use returns whatever was provided. To let a subtree follow a changing value, provide a signal, as Tabs does above, and read it with Signal.get where it's used.

Where Context.use works

Call Context.use in a component body. The value is also right everywhere the body's work continues later:

  • effects the body set up with Effect.run, on every run;
  • the reactive blocks it renders, such as View.tracked, View.Show and View.For, including rows added long after the first render.

Event handlers, timers and promise callbacks run outside any render, so use returns the default there. Read the value in the body and close over it:

1let currentTheme = Context.use(theme)
2<button onClick={_ => Console.log(currentTheme)}> {"Log theme"} </button>

Server rendering

Server rendering and hydration see the same provided values as the browser render, and nothing provided during one render is left behind for the next.

Summary

Context makes a value available to everything a component renders without passing it through intermediate components. A provision is scoped to the providing component instance: only its rendered subtree sees it, and two instances can provide different values. Context values are not reactive by themselves; to share something that changes, provide a Signal.t and read it with Signal.get where it is displayed. Context.use MUST be called in a component body (during render); outside a render it returns the default.

Availability

ItemModule / entryStable sinceChanged in 7.2.0PPX required
Context.make, Context.use, Context.provide, Context.provider, <Context.Provider>xote · xote/context7.2.0 (new)—no

Before 7.2.0 there is no context: use module-level signals, or pass signals as props.

Rules

  1. Context.make(default) declares a context of type Context.t<'a>. Each call creates a distinct context; identity is the value returned, so declare contexts once, at module level, and share that binding.
  2. Context.use(ctx) returns the value of the nearest provider above the calling component, or default when there is none.
  3. Call Context.use in a component body. The value it returns is fixed for that render. Reads inside effects created by the body, and inside reactive regions the body renders (View.tracked, View.Show, View.For, if/switch regions, keyed rows built on later updates), see the same provisions on every later run.
  4. Outside a render — event handlers, timers, promise callbacks, module level — there is no provider in scope and Context.use returns the default. Read the value in the body and close over it.
  5. Context.provide(ctx, value) provides value to everything the calling component renders (its result). It MUST be called in a component body; anywhere else (module level, event handler, inside an effect even on its first run) it throws a JavaScript Error: [Xote] Context.provide was called outside a component body. Call it while the component renders, or use <Context.Provider>.
  6. A provision is visible only to the providing component's result: siblings, the component's parent and anything rendered outside it never see it. The nearest provider wins.
  7. <Context.Provider context=ctx value=v> children </Context.Provider> and Context.provider(ctx, v, children) provide v to children; they are equivalent to calling provide in a component that renders children.
  8. value is a user-component prop: value={Signal.get(x)} is a one-shot read. Providing a value does not make it reactive. To let consumers follow changes, provide the Signal.t (or a Computed) itself, and have consumers read it with Signal.get in their JSX.
  9. Each instance of a component that calls Context.provide(ctx, Signal.make(...)) in its body provides its own signal; this is the mechanism for per-instance shared state (tabs, forms, accordions).
  10. A component body that throws leaves no provision behind.
  11. View.onMount callbacks, portal children (View.Portal) and error boundary subtrees run under the context of the place they are rendered.
  12. A region outside a provider keeps its own (outer) context even when a write inside the provider is what caused it to update.

API

NameSignatureBehaviour
Context.make'a => Context.t<'a>Declares a context with a default.
Context.useContext.t<'a> => 'aNearest provided value, or the default.
Context.provide(Context.t<'a>, 'a) => unitProvides to the calling component's result; body only.
Context.provider(Context.t<'a>, 'a, View.node) => View.nodeFunction form of Provider.
Context.Providerprops {context: Context.t<'value>, value: 'value, children?: View.node}Component form.

Patterns

Static value with a default. Use when: configuration a subtree reads (theme name, locale) that does not change after render.

1let theme = Context.make("light")
2
3module Badge = {
4 @xote.component
5 let make = () => <span class={Context.use(theme)}> {"New"} </span>
6}
7
8module Page = {
9 @xote.component
10 let make = () =>
11 <div>
12 <Badge /> // "light"
13 <Context.Provider context=theme value="dark">
14 <Badge /> // "dark"
15 </Context.Provider>
16 </div>
17}

Per-instance shared state. Use when: a compound component's parts share state and each instance needs its own copy.

1let selection: Context.t<Signal.t<int>> = Context.make(Signal.make(0))
2
3module Tab = {
4 @xote.component
5 let make = (~index: int, ~label: string) => {
6 let selected = Context.use(selection)
7 <button
8 class={Signal.get(selected) == index ? "tab active" : "tab"}
9 onClick={_ => Signal.set(selected, index)}>
10 {label}
11 </button>
12 }
13}
14
15module Tabs = {
16 @xote.component
17 let make = (~children: View.node) => {
18 Context.provide(selection, Signal.make(0))
19 <div role="tablist"> {children} </div>
20 }
21}
22
23<Tabs> <Tab index=0 label="One" /> <Tab index=1 label="Two" /> </Tabs>

Value used in an event handler. Use when: a handler needs the context value.

1module Logger = {
2 @xote.component
3 let make = () => {
4 let current = Context.use(theme) // read during render
5 <button onClick={_ => Console.log(current)}> {"Log theme"} </button>
6 }
7}

Function form. Use when: building nodes without JSX components.

1let node = Context.provider(theme, "contrast", <Badge />)

Context or module-level signal

NeedUse
One value for the whole client appModule-level Signal.make (simpler, no provider).
Different values for different subtreesContext.
One copy per instance of a componentContext providing a Signal.make created in that component's body.
Per-request data during SSRContext (module-level signals are shared by all requests in a server process).

Anti-patterns

Reading context in an event handler.

1<button onClick={_ => Console.log(Context.use(theme))}> {"Log"} </button>

Symptom: always logs the default ("light"), even under a provider. Fix: read in the body (let current = Context.use(theme)) and use current in the handler. Why: handlers run outside any render, where no provider is in scope.

Providing a snapshot.

1<Context.Provider context=theme value={Signal.get(themeSignal)}> {children} </Context.Provider>

Symptom: consumers keep the first value after themeSignal changes. Fix: declare Context.t<Signal.t<string>>, provide themeSignal, and read Signal.get(Context.use(theme)) in consumers' JSX.

Declaring a context inside a component.

1@xote.component
2let make = (~children: View.node) => {
3 let local = Context.make(0) // a new context per instance
4 Context.provide(local, 1)
5 children
6}

Symptom: consumers that use a module-level context never see this value (different identity). Fix: declare the context once at module level and provide it in the body.

Calling provide outside a body.

1Effect.run(() => {
2 Context.provide(theme, "dark")
3 None
4})

Symptom: throws [Xote] Context.provide was called outside a component body…. Fix: call Context.provide directly in the body, or use <Context.Provider>.

Expecting a sibling to see a provision.

Symptom: a component next to (not inside) the provider reads the default. Fix: move the provider up so both are inside it.

Edge cases

  • The default given to Context.make is one value shared by every reader without a provider. A default Signal.make(0) is therefore one global signal for all unprovided readers.
  • Context.use in a body that is re-run (branch swap, keyed row rebuilt, boundary reset) reads the current provision at that time.
  • Contexts are not typed by name: two Context.make("light") calls are unrelated contexts of the same type.
  • Nothing is reactive about switching providers: a consumer is not moved between providers; it keeps what it read in its body.

SSR and hydration

  • Server rendering sees provided values like the client; context is the correct place for per-request data (current user, locale, request URL) because it does not outlive the render.
  • Hydration re-runs bodies on the client, so providers MUST provide the same values on both sides (for example, transfer request data with SSRState and provide it on the client).

Verify

  • jsdom: render <Badge /> outside and inside a provider; assert the two class names differ.
  • Two <Tabs> instances: click a tab in one; assert the other's active tab is unchanged.
  • Handler reads: assert a handler that closes over a body read sees the provided value.
  • Runtime error text "Context.provide was called outside a component body" means a provide call outside a body (rule 5).
  • /docs/learn/components — state placement table.
  • /docs/learn/signals — providing signals for reactive context.
  • /docs/advanced/ssr — per-request data and state transfer.
  • /docs/learn/lifecycle — onMount, portals and boundaries run under the render's context.