Skip to content

provideContext

ts
provideContext<T>(el: Element, key: ContextKey<T>, value: T): { value: T; dispose: () => void }

Provides a value to the subtree of el.

Usage

ts
const { 
value
,
dispose
} =
provideContext
(
el
,
Key
, 42);

Parameters

  • el — the element that owns the scope.
  • key — a ContextKey.
  • value — provided as it is. Nothing is wrapped.

Return value

  • value — the value, so the call can be an expression.
  • dispose — stops answering for this key on this element.

From a component

$provide() is the same call with the element filled in, and it returns the value directly so it reads as a field initializer:

ts
class 
Counter
extends
Base
{
static
config
= {
name
: 'Counter' };
count
= this.
$provide
(
CountContext
,
signal
(0));
}

$provide() is instance-scoped

It is never released, and it dies with the instance or its element. A component whose declaration is withdrawn keeps providing until its element goes — which is why the call belongs in the constructor or a field initializer, not in mounted().

Nearest wins

The scope is the subtree, and a nearer provider shadows a further one by answering first and stopping propagation.

It replays pending requests

A consumer that asked before any provider existed has a pending request with no first answer. provideContext() replays those requests, which is what makes mount order irrelevant: a child that mounts before its coordinator still gets its answer when the coordinator arrives.

Only a mounted provider answers.

Page-wide

For state that belongs to the page rather than to a subtree, use provideRootContext().

MIT Licensed