ContextNew in 7.2
Make a value available to everything a component renders, scoped to that component.
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
Tabson a page each need their own selected tab, shared with their ownTabchildren. A module-level signal can only hold one. - Children you don't write. A component that receives
childrenfrom 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))23module Tabs = {4 @xote.component5 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.component3 let make = (~index: int, ~label: string) => {4 let selected = Context.use(selection)5 <button6 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.ShowandView.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
| Item | Module / entry | Stable since | Changed in 7.2.0 | PPX required |
|---|---|---|---|---|
Context.make, Context.use, Context.provide, Context.provider, <Context.Provider> | xote · xote/context | 7.2.0 (new) | — | no |
Before 7.2.0 there is no context: use module-level signals, or pass signals as props.
Rules
Context.make(default)declares a context of typeContext.t<'a>. Each call creates a distinct context; identity is the value returned, so declare contexts once, at module level, and share that binding.Context.use(ctx)returns the value of the nearest provider above the calling component, ordefaultwhen there is none.- Call
Context.usein 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/switchregions, keyed rows built on later updates), see the same provisions on every later run. - Outside a render — event handlers, timers, promise callbacks, module level — there is no provider in scope and
Context.usereturns the default. Read the value in the body and close over it. Context.provide(ctx, value)providesvalueto 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 JavaScriptError:[Xote] Context.provide was called outside a component body. Call it while the component renders, or use <Context.Provider>.- 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.
<Context.Provider context=ctx value=v> children </Context.Provider>andContext.provider(ctx, v, children)providevtochildren; they are equivalent to callingprovidein a component that renderschildren.valueis 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 theSignal.t(or aComputed) itself, and have consumers read it withSignal.getin their JSX.- 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). - A component body that throws leaves no provision behind.
View.onMountcallbacks, portal children (View.Portal) and error boundary subtrees run under the context of the place they are rendered.- A region outside a provider keeps its own (outer) context even when a write inside the provider is what caused it to update.
API
| Name | Signature | Behaviour |
|---|---|---|
Context.make | 'a => Context.t<'a> | Declares a context with a default. |
Context.use | Context.t<'a> => 'a | Nearest provided value, or the default. |
Context.provide | (Context.t<'a>, 'a) => unit | Provides to the calling component's result; body only. |
Context.provider | (Context.t<'a>, 'a, View.node) => View.node | Function form of Provider. |
Context.Provider | props {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")23module Badge = {4 @xote.component5 let make = () => <span class={Context.use(theme)}> {"New"} </span>6}78module Page = {9 @xote.component10 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))23module Tab = {4 @xote.component5 let make = (~index: int, ~label: string) => {6 let selected = Context.use(selection)7 <button8 class={Signal.get(selected) == index ? "tab active" : "tab"}9 onClick={_ => Signal.set(selected, index)}>10 {label}11 </button>12 }13}1415module Tabs = {16 @xote.component17 let make = (~children: View.node) => {18 Context.provide(selection, Signal.make(0))19 <div role="tablist"> {children} </div>20 }21}2223<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.component3 let make = () => {4 let current = Context.use(theme) // read during render5 <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
| Need | Use |
|---|---|
| One value for the whole client app | Module-level Signal.make (simpler, no provider). |
| Different values for different subtrees | Context. |
| One copy per instance of a component | Context providing a Signal.make created in that component's body. |
| Per-request data during SSR | Context (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.component2let make = (~children: View.node) => {3 let local = Context.make(0) // a new context per instance4 Context.provide(local, 1)5 children6}
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 None4})
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.makeis one value shared by every reader without a provider. A defaultSignal.make(0)is therefore one global signal for all unprovided readers. Context.usein a body that is re-run (branch swap, keyed row rebuilt, boundaryreset) 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
SSRStateand 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
providecall outside a body (rule 5).
Related
/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.