completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Context and dependency injection

Learn web components context: the community protocol, providers and consumers as controllers, nested and late providers, and dependency injection.

By the end, you can
  • 01
    Use the context protocolFire a context-request event that bubbles and is composed, and answer it from the nearest provider with stopImmediatePropagation() and the callback.
  • 02
    Build providers and consumersWrite a provider and a consumer as controllers, with subscriptions, a root for late providers, and the same protocol Lit's @lit/context follows.
  • 03
    Inject servicesHand a logger to deep components through context, give one part of the page its own value, and swap in a fake for a test.

What is context in web components?

Asha runs the Leaf and Kettle web shop. The shop sells in euros, so every price must say EUR. But the prices sit deep inside the tea cards, in their shadow roots. The page can't reach them. And next month, the airport counter opens. It sells in pounds.

The card in the middle doesn't care about money. It shows a name and a price. How does a price deep inside it learn the currency, without every component on the way passing it down?

With context. A component that needs a value fires a context-request event. The event bubbles up through the page, and out of every shadow root on the way. The nearest ancestor that provides that value answers it by calling the event's callback. Nothing in between has to know.

Here it is in the tea kit. One element provides the currency, and the two cards say nothing about it:

The kit's tea-currency around two cardsPop out in the code editor (opens in a new tab)HTML
<tea-currency code="EUR">  <tea-card name="Sencha" price="4"></tea-card>  <tea-card name="Oolong" price="5"></tea-card></tea-currency><script type="module">  import "./tea-kit/index.js";</script>
ResultLoading…
  • Line 1 is tea-currency, new in this lesson. It provides the code EUR to everything inside it.
  • Lines 2 and 3 are the kit's cards. They have a name and a price, and no word about currency.

The cards show Price: 4 EUR and Price: 5 EUR. Each card draws its price line with a tea-price in its own shadow root. That price asked for the currency, and tea-currency answered.

A row of four cards joined by arrows that point right: tea-price, shadow root, tea-card, and tea-currency. Above the row, the words asks for the currency. The tea-price card is labeled consumer, and the tea-currency card provider. A curved arrow goes back from tea-currency to tea-price, labeled callback EUR.asks for the currencyconsumerprovidertea-priceshadow roottea-cardtea-currencycallback("EUR")
The price asks. Its request leaves the card's shadow root, because it's composed, passes the card, and reaches tea-currency. The provider answers by calling the request's callback with EUR.
Real-life analogyAsking for the manager on your floor

A new worker starts on the third floor of a big store. She asks, "Who's the manager here?" The question goes to the people around her. The third floor's manager answers. The store manager on the top floor never hears the question. If the third floor had no manager, the question would go up until someone answered.

In real life: A new worker who asks who the manager is
In JavaScript: A consumer that fires context-request
In real life: The word manager in the question
In JavaScript: The context key, like currencyContext
In real life: The manager on the same floor
In JavaScript: The nearest provider
In real life: The answer stops there
In JavaScript: stopImmediatePropagation()
The main idea

A consumer asks; the nearest provider answers. The consumer fires a context-request event that bubbles and is composed. It carries a key, which says what it wants, and a callback. The nearest ancestor that provides that key stops the event and calls the callback with its value.

Lesson 18.4 passed data down and sent events up. Lesson 19.3 built controllers. This lesson builds context from both: an event that goes up, and two controllers that send and answer it.

What is prop drilling?

Prop drilling means passing a value down through every component between its owner and the one that uses it. Each one in the middle takes the value only to hand it on. The context protocol calls this undesirable, because the components in the middle must know about data their children need (lines 13 to 15).

Here is a small shelf of tea tiles. Each tile draws a tea-price in its shadow root. Try both ways of getting the currency to the prices:

Playground: pass it down, or use context
A shelf of tiles in eurosPop out in the code editor (opens in a new tab)HTML
<tea-shelf currency="EUR"></tea-shelf><script type="module">  import "./tea-shelf.js";</script>
ResultLoading…
Try it yourself
Every component in the middle carries the currency

The shelf hands its currency to each tile, and each tile hands it to its price. The tile never shows a currency itself, but it needs two lines to carry one.

The page is the same. The tea-shelf.js and tea-tile.js tabs change.

Both show Price: 4 EUR and Price: 5 EUR. Now look at the tile in the first choice:

tea-tile.js, passing it downJavaScript
import { TeaElement } from "./tea-kit/element.js";
import "./tea-kit/tea-price.js";

class TeaTile extends TeaElement {
  static attributes = { name: {}, price: {}, currency: {} };
  static template = `<strong></strong> <tea-price></tea-price>`;

  render() {
    this.renderRoot.querySelector("strong").textContent = this.name;
    const price = this.renderRoot.querySelector("tea-price");
    price.amount = this.price;
    price.currency = this.currency;
  }
}

customElements.define("tea-tile", TeaTile);
  • Line 5 declares a currency attribute. The tile never shows it.
  • Line 12 hands it to the price. That's the only thing the tile does with it.

Two lines in the tile exist only to carry the currency. With context, the tile has none. Put a section and a list between the shelf and the tiles, and each of them needs the same two lines. Change the currency, and every one of them must pass the new value on.

Real-life analogyPassing the salt down a long table

Asha sits at the far end of a long table, and the salt is at the other end. Every guest on the way has to pick it up and pass it on, even the ones who never eat salt. If Asha could just ask a waiter, nobody else would have to stop eating.

In real life: The salt at one end of the table
In JavaScript: The shelf's currency
In real life: Asha at the other end
In JavaScript: The price that needs it
In real life: Every guest in between
In JavaScript: Every component in the middle
In real life: Asking the waiter instead
In JavaScript: Asking through context

Lesson 18.4 met this problem with its shelf of tiles. It used the shop as a mediator, and a store that components subscribe to (lesson 18.4). Lesson 18.5 shared state through signals. Lit's docs say the same: components that subscribe to data don't need every parent to pass it along (Lit). A store or a signal is one value for the whole page. Context gives each part of the page the value of its nearest provider.

How does the context protocol work?

The context protocol is an agreement about one event, from the W3C Web Components Community Group. The group brings together people who build web component libraries and tools (its README). The protocol isn't a browser feature. It's a pattern that libraries agree to follow (line 45), so components from different makers can work together (line 3). Its status is Candidate, which means it will soon be accepted (lines 35 and 36).

The whole protocol fits on one page, with no library at all:

A provider and a request, with no libraryPop out in the code editor (opens in a new tab)HTML
<div id="shop">  <p id="price">Price: 4</p></div><script type="module">  const shop = document.querySelector("#shop");  shop.addEventListener("context-request", (event) => {    if (event.context !== "currency") return;    event.stopImmediatePropagation();    event.callback("EUR");  });   const request = new Event("context-request", { bubbles: true, composed: true });  request.context = "currency";  request.callback = (value) => console.log("The price got:", value);  document.querySelector("#price").dispatchEvent(request);  console.log("dispatchEvent() returned");</script>
ResultLoading…
  • Lines 1 to 3 are a shop with a price inside it.
  • Lines 6 to 10 are the provider: a listener on the shop. Line 7 checks the request's key. Line 8 stops the event. Line 9 calls the callback with EUR.
  • Line 12 makes the request: an event named context-request that bubbles and is composed.
  • Line 13 adds the context key, which says what is wanted. Line 14 adds the callback: the function the provider calls with the answer.
  • Line 15 fires the request from the price. The price is the consumer.

It prints The price got: EUR, then dispatchEvent() returned. The answer came before dispatchEvent() finished. Listeners run during the dispatch, so the answer is synchronous, as the protocol wants (line 24). A callback is a function you hand to someone else to call (callbacks). Here, it works like a stamped envelope with your address on it: whoever has the answer writes it in and posts it back.

The protocol names the parts (lines 41 to 46):

  • the consumer fires a context-request event;
  • the event carries a context, the key, and a callback;
  • providers listen for the event;
  • a provider that answers calls stopImmediatePropagation() on it.

The kit wraps lines 12 to 14 in a class, so every consumer builds the same event. It's in the new tea-kit/context.js:

context.js: the request eventJavaScript
export class ContextRequestEvent extends Event {
  constructor(context, callback, subscribe = false) {
    super("context-request", { bubbles: true, composed: true });
    this.context = context;
    this.callback = callback;
    this.subscribe = subscribe;
  }
}
  • Line 3 names the event and makes it bubble and compose, every time.
  • Lines 4 to 6 keep the key, the callback, and subscribe, which a later section explains.

Why must the request bubble and be composed?

Bubbling sends an event up through its parents. composed lets it leave a shadow root (lesson 9.2). The protocol asks for both (line 52). Here the price sits in a card's shadow root. Only line 12 changes:

Playground: which options reach the shop?
A request from inside a shadow rootPop out in the code editor (opens in a new tab)HTML
<div id="shop"><div id="card"></div></div><script type="module">  document.querySelector("#shop").addEventListener("context-request", (event) => {    event.stopImmediatePropagation();    event.callback("EUR");  });   const card = document.querySelector("#card").attachShadow({ mode: "open" });  card.innerHTML = "<p>Price: 4</p>";   let answer = "No one answered";  const request = new Event("context-request", { bubbles: true, composed: true });  request.callback = (value) => (answer = `The price got: ${value}`);  card.querySelector("p").dispatchEvent(request);  console.log(answer);</script>
ResultLoading…
Try it yourself
The request leaves the card and reaches the shop

bubbles sends the request up the tree, and composed lets it leave the card's shadow root. The shop hears it and answers.

Only line 12 changes: the options of the request.
  • Lines 3 to 6 are the shop's provider.
  • Lines 8 and 9 give the card a shadow root with a price in it.
  • Line 14 fires the request from that price. Line 15 prints what came back.

With both, it prints The price got: EUR. With only one, it prints No one answered. Nothing warns you. The callback is simply never called. Why it matters: forget composed, and a consumer inside a shadow root can never find a provider outside it.

Why stopImmediatePropagation() and not stopPropagation()?

stopPropagation() stops an event from going on to the next element. Other listeners on the same element still run (stopping an event). Two providers on one element show the difference:

stopPropagation() lets a second listener answerPop out in the code editor (opens in a new tab)JavaScript
const shop = new EventTarget();
shop.addEventListener("context-request", (event) => {
  event.stopPropagation();
  event.callback("EUR");
});
shop.addEventListener("context-request", (event) => event.callback("GBP"));

const request = new Event("context-request");
request.callback = (value) => console.log("Answer:", value);
shop.dispatchEvent(request);
  • Lines 2 to 5: the first listener stops the event, then answers EUR.
  • Line 6: a second listener on the same element answers GBP.

It prints Answer: EUR, then Answer: GBP. Two providers answered one request. Change line 3 to event.stopImmediatePropagation(); and run it again: it prints only Answer: EUR.

The protocol first said stopPropagation(), and changed to stopImmediatePropagation() (line 345). Now a provider that can answer must call it (line 125). It should call it before the callback, so a callback that throws can't leave the event running (lines 133 to 141). Lit's provider still calls stopPropagation() (line 109). That only matters when two providers listen on the same element.

How do you build a context provider and consumer?

Every consumer fires its request when it joins the page. Every one that subscribes should unsubscribe when it leaves. The protocol says exactly that: ask in connectedCallback(), and unsubscribe in disconnectedCallback() (line 188). Those are the moments a controller's hostConnected() and hostDisconnected() run (lesson 19.3). So the kit makes both sides controllers. Here is the consumer:

context.js: ContextConsumerJavaScript
export class ContextConsumer {
  value = undefined;
  #unsubscribe;
  #callback = (value, unsubscribe) => {
    if (unsubscribe !== this.#unsubscribe) this.#unsubscribe?.();
    this.#unsubscribe = unsubscribe;
    this.value = value;
    this.host.requestUpdate();
  };

  constructor(host, { context, subscribe = false }) {
    Object.assign(this, { host, context, subscribe });
    host.addController(this);
  }

  hostConnected() {
    this.host.dispatchEvent(new ContextRequestEvent(this.context, this.#callback, this.subscribe));
  }

  hostDisconnected() {
    this.#unsubscribe?.();
    this.#unsubscribe = undefined;
  }
}
  • Line 2 keeps the answer in value. Line 3 keeps the unsubscribe function, which comes later.
  • Lines 4 to 9 are the callback. Line 7 stores the value, and line 8 asks the host to draw again.
  • Line 13 adds the consumer to its host, like lesson 19.3's controllers.
  • Lines 16 to 18: when the host joins the page, line 17 fires the request from the host.

The callback is a class field, so it's the same function every time this consumer asks. That matters later. Now the provider:

context.js: ContextProviderJavaScript
export class ContextProvider {
  #value;
  #subscribers = new Map();

  constructor(host, { context, initialValue }) {
    Object.assign(this, { host, context });
    this.#value = initialValue;
    host.addEventListener("context-request", this.#onRequest);
    host.addController?.(this);
  }

  get value() {
    return this.#value;
  }

  setValue(value) {
    if (Object.is(value, this.#value)) return;
    this.#value = value;
    for (const [callback, unsubscribe] of this.#subscribers) callback(value, unsubscribe);
  }

  hostConnected() {
    this.host.dispatchEvent(new ContextProviderEvent(this.context, this.host));
  }

  #onRequest = (event) => {
    if (event.context !== this.context) return;
    event.stopImmediatePropagation();
    if (event.subscribe) this.#subscribe(event.callback);
    else event.callback(this.#value);
  };

  #subscribe(callback) {
    if (!this.#subscribers.has(callback)) this.#subscribers.set(callback, () => this.#subscribers.delete(callback));
    callback(this.#value, this.#subscribers.get(callback));
  }
}
  • Line 8 listens on the host from the moment the provider is made. Line 9 adds it as a controller, if the host is one.
  • Lines 26 to 31 answer a request. Line 27 skips other keys. Line 28 stops the event first. Line 30 calls the callback once.
  • Lines 16 to 20 change the value. Line 17 ignores the same value again.

The kit's two new components each use one of them:

tea-price.js: a consumer of the currencyJavaScript
import { ContextConsumer } from "./context.js";
import { currencyContext } from "./contexts.js";
import { TeaElement } from "./element.js";

export class TeaPrice extends TeaElement {
  static attributes = {
    amount: { reflect: true },
    currency: { reflect: true },
  };
  #currency = new ContextConsumer(this, { context: currencyContext, subscribe: true });

  createRenderRoot() {
    return this;
  }

  render() {
    const currency = this.currency ?? this.#currency.value ?? "";
    this.textContent = `Price: ${this.amount} ${currency}`.trim();
  }
}

customElements.define("tea-price", TeaPrice);
  • Line 10 makes the consumer, with the key currencyContext.
  • Line 17 picks the currency. The price's own currency attribute wins. Without one, it uses what the provider answered. Without either, nothing.
tea-currency.js: a provider of the currencyJavaScript
import { ContextProvider } from "./context.js";
import { currencyContext } from "./contexts.js";
import { TeaElement } from "./element.js";

export class TeaCurrency extends TeaElement {
  static attributes = {
    code: { reflect: true },
  };
  #provider = new ContextProvider(this, { context: currencyContext });

  createRenderRoot() {
    return this;
  }

  requestUpdate(name, oldValue) {
    super.requestUpdate(name, oldValue);
    this.#provider.setValue(this.code);
  }
}

customElements.define("tea-currency", TeaCurrency);
  • Line 7 declares the code attribute, like EUR.
  • Line 9 makes the provider, with the same key.
  • Lines 15 to 18 hand the provider every change at once, the way lesson 19.3's form mixin handed the form its value.
  • Lines 11 to 13 draw in its own light DOM. It draws nothing, so its children stay where the page put them.

Lit's @lit/context has the same two controllers, ContextProvider and ContextConsumer (Lit). Its consumer also asks in hostConnected() and unsubscribes in hostDisconnected() (lines 81 to 90). Its provider also listens from its constructor (line 92).

Which provider answers a context request?

The nearest one with the same key. A request starts at the consumer and goes up. The first provider of its key that hears it answers and stops it. So a provider inside another gives its own part of the page its own value. Try it with the airport counter:

Playground: a provider for the airport counter
A shop in euros, with a counter inside itPop out in the code editor (opens in a new tab)HTML
<tea-currency code="EUR">  <tea-card name="Sencha" price="4"></tea-card>  <section>    <h3>Airport counter</h3>    <tea-card name="Oolong" price="5"></tea-card>  </section></tea-currency><script type="module">  import "./tea-kit/index.js";</script>
ResultLoading…
Try it yourself
Every price gets the shop's currency

Both prices ask for the currency. The only provider above them is the outer tea-currency, so both show EUR.

Only lines 3 and 6 change: a section, or a tea-currency for the counter.
  • Line 1 is the shop's provider, in EUR. Line 2 is Sencha's card.
  • Lines 3 to 6 are the airport counter, with Oolong's card on line 5.

With a section, both cards show EUR. With a provider for the counter, Sencha shows Price: 4 EUR and Oolong shows Price: 5 GBP. Like the third floor's manager, the counter's provider answers first, and the shop's never hears the question.

Two rows. Sencha's price: tea-price, then tea-card, then the shaded EUR provider, joined by arrows. It shows Price: 4 EUR, and the EUR provider answers. Oolong's price, at the airport counter: tea-price, then tea-card, then the shaded GBP provider, joined by arrows, then a faded, crossed-out EUR provider with no arrow to it. It shows Price: 5 GBP. The GBP provider answers and stops the request, and the EUR provider never hears it.Sencha's pricetea-pricetea-cardEUR providerPrice: 4 EURanswersOolong's price, at the airport countertea-pricetea-cardGBP providerEUR providerPrice: 5 GBPanswers and stops itnever hears it
Each request goes up until a provider of the same key hears it. The airport's GBP provider is nearer to Oolong's price, so it answers and stops the request. The outer EUR provider never hears it.

This is what makes context different from a store. Lit's docs name themes as a use case: styles for the whole page, or for one part of it (Lit). Why it matters: one component file can show different values in different parts of the page, with no change to its code.

How do providers and consumers match keys?

A provider answers only a request whose key is === its own (line 81). A key can be any value (line 77). Strings and Symbols behave differently:

Two strings match, and two Symbols never doPop out in the code editor (opens in a new tab)JavaScript
console.log("currency" === "currency");
console.log(Symbol("currency") === Symbol("currency"));

const currencyContext = Symbol("currency");
console.log(currencyContext === currencyContext);

It prints true, false, and true. Line 2 makes two Symbols with the same description, and they're still different (Symbols). Line 5 compares one Symbol with itself.

Lit's docs say a string key can clash: two modules might use "logger" for different things. So they suggest a Symbol, which is unique (Lit). The kit keeps its keys in tea-kit/contexts.js, and both sides import them from there:

contexts.js: the kit's currency keyJavaScript
import { createContext } from "./context.js";

export const currencyContext = createContext(Symbol("currency"));

Line 3 makes the key. createContext() just gives back what you pass it. Lit's does the same (Lit).

How do context subscriptions work?

A provider's value can change. The shop might switch to pounds. A consumer that wants every new value says so with subscribe: true in its request. Then the provider keeps its callback, and calls it again for each change (line 127). Try a total that subscribes, and one that doesn't. Press Switch to GBP:

Playground: subscribe, or ask once
A total, before and after the switchPop out in the code editor (opens in a new tab)HTML
<tea-currency code="EUR">  <p><tea-total></tea-total></p></tea-currency><button id="switch">Switch to GBP</button><script type="module">  import "./tea-kit/index.js";  import "./tea-total.js";  const total = document.querySelector("tea-total");  await total.updateComplete;  console.log(total.textContent);  document.querySelector("#switch").addEventListener("click", async () => {    document.querySelector("tea-currency").code = "GBP";    await total.updateComplete;    console.log(total.textContent);  });</script>
ResultLoading…
Try it yourself
The total follows the change

The provider keeps the total's callback. When the code changes, it calls the callback again with GBP, and the total draws again.

Only line 6 of the tea-total.js tab changes: subscribe: true or false.
  • Line 2 is a total inside the shop. Lines 9 and 10 print it once it has drawn.
  • Line 12 switches the shop's code. Lines 13 and 14 print the total again.

Both print Total: 9 EUR first. After the switch, the subscriber prints Total: 9 GBP, and the other still prints Total: 9 EUR. The protocol says a provider must not keep the callback of a request that didn't subscribe. Keeping it could hold on to the consumer forever (line 129).

Real-life analogyA newsletter with one unsubscribe link

Asha signs up for the tea market's newsletter. Each week a new issue arrives. At the bottom of each one is the same unsubscribe link. One click, and the issues stop. Someone who only asked for this week's prices gets one letter, and no more.

In real life: Signing up for the newsletter
In JavaScript: A request with subscribe: true
In real life: Each new issue in your mailbox
In JavaScript: The callback, called with each new value
In real life: The unsubscribe link at the bottom
In JavaScript: The unsubscribe function
In real life: The same link in every issue
In JavaScript: The same function in every call

Back in the provider's code, line 29 sends a subscribing request to #subscribe(). Line 34 makes one unsubscribe function for each callback, and keeps both in a Map. A consumer's callback is always the same function, so each consumer has one entry, however often it asks. Line 35 answers with the value and that function. Line 19 hands every subscriber the new value, with the same function again.

Why the same function? The consumer's line 5 compares it. A different unsubscribe function means a different provider answered, so the consumer leaves the old one. The protocol's own example does that (lines 199 to 203), and so does Lit's consumer (lines 107 to 113). A provider that makes a new function each time makes its subscribers leave. Exercise 5 finds that bug.

When the total leaves the page, the consumer's hostDisconnected() calls the unsubscribe function, on line 21 of its code. The provider forgets the callback. When the total comes back, hostConnected() asks again. The protocol also suggests that providers hold callbacks in WeakRefs, in case a consumer never unsubscribes (line 131).

What if the provider is defined after the consumer?

A consumer asks once, when it connects. If no provider listens at that moment, the request goes up to the top of the page, and is gone. That happens when the provider's class is defined later than the consumer's. Until then, the provider is an undefined element, with no listener (lesson 4.1).

The kit itself has this trap. Its index.js loads each component in turn. If it loaded tea-currency after tea-price, the overview's prices would ask before any provider could answer. They would show Price: 4 and Price: 5. So the kit defines tea-currency first.

A page can't always do that. Here, tea-front's code loads only when you press its button. Press Load tea-front, with each choice:

Playground: a provider that loads late
A price inside tea-front, before tea-front is definedPop out in the code editor (opens in a new tab)HTML
<tea-front>  <p><tea-price amount="4"></tea-price></p></tea-front><button id="load">Load tea-front</button><script type="module">  import "./root.js";  import "./tea-kit/tea-price.js";  const price = document.querySelector("tea-price");  await price.updateComplete;  console.log("Before:", price.textContent);  document.querySelector("#load").addEventListener("click", async () => {    await import("./tea-front.js");    await price.updateComplete;    console.log("After:", price.textContent);  });</script>
ResultLoading…
Try it yourself
The price asked too early

The price asked when the page loaded. No one answered, and the request was gone. tea-front now listens, but no one asks again.

Only the root.js tab changes: no root, the kit's ContextRoot, or Lit's. The Lit choice loads @lit/context 1.1.6.
  • Line 6 loads root.js first. Line 7 loads the price, which asks at once.
  • Line 12 loads tea-front.js, which defines tea-front. Lines 13 and 14 print the price again.

Every choice prints Before: Price: 4. With no root, it then prints After: Price: 4: the price never learned the currency. With either root, it prints After: Price: 4 EUR.

Real-life analogyThe front desk keeps your question

Asha asks for the manager on her first morning, but the manager hasn't arrived yet. The front desk writes her question down. When the manager walks in, the desk hands it over, and the manager comes to find her.

In real life: Your question with no one to answer it
In JavaScript: A request no provider answered
In real life: The front desk that writes it down
In JavaScript: The ContextRoot
In real life: The new manager arriving
In JavaScript: The provider connecting
In real life: The desk passing on your question
In JavaScript: The root asking again, from the consumer

Lit's ContextRoot gathers requests no provider answered, and sends them again when a matching provider arrives (Lit). The kit's root does the same, in context.js:

context.js: ContextRootJavaScript
export class ContextRoot {
  #waiting = new Map();

  attach(element) {
    element.addEventListener("context-request", this.#onRequest);
    element.addEventListener("context-provider", this.#onProvider);
  }

  detach(element) {
    element.removeEventListener("context-request", this.#onRequest);
    element.removeEventListener("context-provider", this.#onProvider);
  }

  #onRequest = (event) => {
    if (event.subscribe) this.#waiting.set(event.callback, { context: event.context, consumer: event.composedPath()[0] });
  };

  #onProvider = (event) => {
    const waiting = [...this.#waiting].filter(([, request]) => request.context === event.context);
    for (const [callback, { context, consumer }] of waiting) {
      this.#waiting.delete(callback);
      consumer.dispatchEvent(new ContextRequestEvent(context, callback, true));
    }
  };
}
  • Lines 4 to 7 listen on an element, usually document.body. A request no one answered reaches it.
  • Line 15 keeps a request that subscribes, with its callback and its consumer. composedPath()[0] is where the request started, even inside a shadow root (lesson 9.1).
  • Lines 18 to 24 run when a context-provider event arrives. Line 22 sends each waiting request for that key again, from its consumer.
Three numbered rows. Row 1, the price asks and no one answers: an arrow from tea-price to ContextRoot, which keeps the request. Row 2, tea-front is defined and connects: an arrow from tea-front to ContextRoot, which hears context-provider. Row 3, the root asks again from the price: arrows from ContextRoot to tea-price to tea-front, which answers EUR.1. The price asks, and no one answerstea-priceContextRootkeeps the request2. tea-front is defined, and connectstea-frontContextRoothears context-provider3. The root asks again, from the priceContextRoottea-pricetea-frontanswers EUR
No provider answered the price, so its request reached the root, which kept it. When tea-front connects, it fires context-provider. The root sends the request again from the price, and this time tea-front answers.

Who fires context-provider? The provider, in hostConnected(), on line 23 of its code. That event isn't part of the protocol. It's Lit's, fired by its provider when it connects (lines 165 to 168). The kit fires the same event, with the same fields, so Lit's root asks again for the kit's consumers too.

Three things to know about roots:

  • Both roots keep only requests that subscribe (lines 92 to 95). A consumer that asks once is never asked for again. Exercise 6 shows it.
  • The root must be listening before anything asks. A module's imports run in the order they're written (evaluation order), so root.js comes first.
  • Lit's root keeps consumers in WeakRefs, so a consumer removed while it waits can still be freed (lines 31 to 34). The kit's keeps them until a provider of their key arrives.

One more late provider hides inside a single component. TeaElement stamps a static template in its constructor (lesson 19.1). A subclass's fields, like #provider, run after that. So a provider that put its tiles in its template would miss their requests. The shelf in the playground draws its tiles in render() instead, after its provider exists.

Does Lit context work with other web components?

Yes. Lit's docs say its context is based on the community protocol, so a Lit element can provide data to a consumer not built with Lit, and the other way round (Lit). Prove it. Each choice mixes the kit with @lit/context. Press Switch to GBP:

Playground: the kit and Lit, both ways
A shop front and a price tag, from two librariesPop out in the code editor (opens in a new tab)HTML
<shop-front>  <p><price-tag></price-tag></p></shop-front><button id="switch">Switch to GBP</button><script type="module">  import "./shop-front.js";  import "./price-tag.js";  const price = document.querySelector("price-tag");  await price.updateComplete;  console.log(price.textContent);  document.querySelector("#switch").addEventListener("click", async () => {    document.querySelector("shop-front").provider.setValue("GBP");    await price.updateComplete;    console.log(price.textContent);  });</script>
ResultLoading…
Try it yourself
A Lit provider answers the kit's consumer

The shop front is a LitElement with @lit/context's ContextProvider. The price tag is built on TeaElement, with the kit's ContextConsumer. They share only the protocol and the key.

The page is the same. The shop-front.js and price-tag.js tabs change. Both choices load Lit 3.3.3 and @lit/context 1.1.6.
  • Lines 1 to 3 are a shop front with a price tag inside it.
  • Line 12 calls the provider's setValue(). The kit's provider and Lit's both have one.

Both choices print Price: 4 EUR, then Price: 4 GBP. Only lines 1 to 3, the class's parent, and the price tag's drawing change between libraries. The two sides share the event, the key, and the callback, and nothing else.

Two small differences don't get in the way:

  • Lit's request event has one more field, contextTarget: the element that asked (lines 67 to 78). Without it, Lit's provider uses composedPath()[0] (line 105).
  • Both providers keep one unsubscribe function for each callback: the kit's on line 34, and Lit's in its value notifier (lines 60 to 80). So each library's consumer keeps its subscription to the other's provider.

Why it matters: a design system can ship components built with Lit, and an app can wrap them in providers it wrote itself, or the other way round.

What is dependency injection in web components?

A dependency is something a component uses but doesn't make itself, like a logger or an API client. Dependency injection means someone else hands it in. The JavaScript course uses it to swap in fakes for tests (mocks and fakes). Lit's docs name services, like loggers, analytics, and data stores, as a use case for context (Lit). Here an order button logs through whatever logger its nearest provider hands in:

tea-order.js: a button that asks for a loggerJavaScript
import { ContextConsumer } from "./tea-kit/context.js";
import { TeaElement } from "./tea-kit/element.js";
import { loggerContext } from "./logger.js";

class TeaOrder extends TeaElement {
  static template = `<button>Order Sencha</button>`;
  #logger = new ContextConsumer(this, { context: loggerContext });

  constructor() {
    super();
    this.renderRoot.querySelector("button").addEventListener("click", () => {
      this.#logger.value.log("Ordered Sencha");
    });
  }
}

customElements.define("tea-order", TeaOrder);
  • Line 7 asks for loggerContext, a Symbol key from the logger.js tab.
  • Line 12 logs through it. The button never knows which logger it got.

Now give it two different providers. Press Order Sencha in the app:

Playground: the same order, two loggers
tea-order in the app, and in a testPop out in the code editor (opens in a new tab)HTML
<tea-app>  <tea-order></tea-order></tea-app><script type="module">  import "./tea-app.js";  import "./tea-order.js";</script>
ResultLoading…
Try it yourself
The app hands in its logger

tea-app provides the shop's logger. Press Order Sencha: the order asks its provider for a logger, and gets the one that prints Shop log.

The tea-order.js tab is the same in both. The app uses tea-app.js; the test uses test-app.js.

In the app, it prints Shop log: Ordered Sencha. In the test, it prints The fake logger saw: Ordered Sencha. Here is the test's provider:

test-app.js: a provider with a fake loggerJavaScript
import { ContextProvider } from "./tea-kit/context.js";
import { TeaElement } from "./tea-kit/element.js";
import { loggerContext } from "./logger.js";

export const seen = [];
const logger = { log: (text) => seen.push(text) };

class TestApp extends TeaElement {
  #logger = new ContextProvider(this, { context: loggerContext, initialValue: logger });

  createRenderRoot() {
    return this;
  }
}

customElements.define("test-app", TestApp);
  • Lines 5 and 6 are the fake. It only keeps each line, so a test can read them.
  • Line 9 provides it, under the same key the app uses.
Two halves. In the app: a tea-app card with a shaded real logger card under it, and an arrow labeled hands it in down to a tea-order card. Under it, Shop log: Ordered Sencha. In a test: a test-app card with a shaded fake logger card under it, and an arrow labeled hands it in down to the same tea-order card. Under it, kept: Ordered Sencha.In the apptea-appreal loggerhands it intea-orderShop log: Ordered SenchaIn a testtest-appfake loggerhands it intea-orderkept: Ordered Sencha
The same tea-order asks for a logger in both. In the app, tea-app hands in the real one. In a test, test-app hands in a fake that only keeps each line. tea-order never changes.
Real-life analogyThe practice knife in the training kitchen

At Leaf and Kettle, cooks don't bring their own knives. They ask, and the kitchen hands one over. In the training kitchen, a new cook gets a blunt practice knife. The cook works the same way in both kitchens.

In real life: A cook who asks for a knife
In JavaScript: tea-order, asking for loggerContext
In real life: The kitchen that hands one over
In JavaScript: The nearest provider
In real life: The sharp knife in the real kitchen
In JavaScript: The app's logger
In real life: The blunt practice knife in training
In JavaScript: The fake logger in a test

Compare an order that imports its logger:

An order that imports its loggerJavaScript
import { logger } from "./logger.js";

class TeaOrder extends TeaElement {
  // ...
  order() {
    logger.log("Ordered Sencha");
  }
}

Line 1 decides the logger when the file loads. Every page, and every test, gets that one. Lit's docs name two advantages of context over a shared module: late coupling and tree scoping (Lit). Late coupling means the page picks the logger, not the component. Tree scoping means each part of the page can get its own. Read each row across:

Three ways to get a value to a deep component
QuestionPass it downImport a moduleContext
Do the components in between need code for it?Yes. Each one takes the value and hands it on.No. Each component imports it itself.No. The request travels up past them.
Can one part of the page get its own value?Yes, if every parent on the way passes the right one.No. Every component that imports it gets the same one.Yes. The nearest provider decides.
Can a test hand in a fake?Yes, by setting it on the component.Only by changing the module for the whole page.Yes. Wrap the component in a test provider.
Does a new value reach the component?Yes, when each parent passes it down again.Only if the module tells everyone who imported it.Yes, when the consumer subscribes.
Where is it in this lesson?The shelf's Pass it down choice.The order that imports its logger.tea-currency, the shelf's Use context choice, and tea-app.

The protocol keeps its own job small. It says it isn't a dependency injection framework, and doesn't cover other ways of injecting, like constructor injection. It only shares data by where an element sits in the DOM (lines 29 to 31). It isn't a state manager either, though a component can find a store through it (lines 33 to 37).

Adding context to the tea kit

This version of the kit is kitAfter194. Three files are new, and three change:

  • tea-kit/context.js, new: createContext(), the two events, ContextProvider, ContextConsumer, and ContextRoot.
  • tea-kit/contexts.js, new: currencyContext, a Symbol key.
  • tea-kit/tea-currency.js, new: the provider element. index.js loads it first.
  • tea-kit/tea-price.js: it consumes the currency, unless it has a currency attribute.
  • tea-kit/tea-card.js: its price line is a tea-price in its shadow root. With no provider around it, it shows Price: 4, as before.
  • tea-kit/custom-elements.json: the card's new price line, and the four new modules.

Here they work with the kit's shop from lesson 18.4. Press Add on Sencha:

The kit's shop in euros, and the airport counter in poundsPop out in the code editor (opens in a new tab)HTML
<tea-currency code="EUR">  <tea-shop></tea-shop>  <tea-currency code="GBP">    <h2>Airport counter</h2>    <tea-card name="Matcha" price="6"></tea-card>  </tea-currency></tea-currency><script type="module">  import "./tea-kit/index.js";  document.querySelector("tea-shop").teas = [    { id: 1, name: "Sencha", price: 4 },    { id: 2, name: "Oolong", price: 5 },  ];  document.addEventListener("tea-add", (event) => console.log("Added:", event.tea));</script>
ResultLoading…
  • Line 2 is the kit's shop. Lines 10 to 13 give it two teas.
  • Lines 3 to 6 are the airport counter, with its own provider in GBP.
  • Line 14 prints each tea-add that comes up from a card.

The shop's cards show Price: 4 EUR and Price: 5 EUR. Each price asked from inside its card's shadow root, inside the shop's shadow root. Matcha shows Price: 6 GBP. Add prints Added: Sencha, and the cart works as before. Neither the shop nor the card has a line about currency.

Where should each value travel? Sort them:

Which way should it travel?
  • The name of the tea on one card
  • The reader pressed Add on a card
  • The currency every price on the page shows
  • A logger that many components use, and that a test swaps for a fake
  • The number a card's tea-quantity starts at, set by the card
  • A tab was picked, and the tab list must hear about it
Try it yourself
0 of 6 correct

Sort each value by how it should reach the component that needs it.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Common mix-ups

  • "Context is a global store." No. Each consumer gets the value of its nearest provider. The airport counter got GBP while the shop around it had EUR.
  • "A request only needs to bubble." No. Without composed, it stops at the first shadow root. The playground printed No one answered.
  • "Every provider above the consumer answers." No. The nearest provider of the key answers, and stops the request with stopImmediatePropagation().
  • "Two Symbol('currency') keys are the same key." No. Every Symbol is unique. Share one key from one module.
  • "A consumer always finds its provider." No. One that asks before its provider is defined gets nothing, unless a root asks again.
  • "A consumer gets every new value." No. Only with subscribe: true. Without it, the provider answers once.
  • "Context is a dependency injection framework." No. The protocol says it isn't. It finds a value by where an element sits, and you can build injection on that.
  • "Lit context only works with Lit components." No. The kit's consumer took Lit's value, and Lit's consumer took the kit's.

Practice exercises

Exercise 1 · Warm-upPredict the nearest provider

Two providers sit around one card. What does the Matcha card's price show?

<tea-currency code="EUR">  <tea-currency code="GBP">    <tea-card name="Matcha" price="6"></tea-card>  </tea-currency>  <p><tea-price amount="3" currency="USD"></tea-price></p></tea-currency><script type="module">  import "./tea-kit/index.js";</script>
ResultLoading…

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upPredict when the callback runs

    A shop answers a request. Predict the four lines, in order, then run it.

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    const shop = new EventTarget();
    shop.addEventListener("context-request", (event) => {
      console.log("The shop answers");
      event.callback("EUR");
    });
    
    const request = new Event("context-request");
    request.callback = (value) => console.log("The price got:", value);
    console.log("Before dispatchEvent()");
    shop.dispatchEvent(request);
    console.log("After dispatchEvent()");

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeFind why the counter's price shows EUR

      A hand-written tea-counter should give Oolong's card GBP. The card shows EUR. Fix the counter.js tab. What does Oolong's price show then?

      <tea-currency code="EUR">  <tea-counter code="GBP">    <tea-card name="Oolong" price="5"></tea-card>  </tea-counter></tea-currency><script type="module">  import "./counter.js";  import "./tea-kit/index.js";</script>
      ResultLoading…

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeFind why the test's fake saw nothing

        This test uses the fake logger from the playground. But the page shows a TypeError, and the fake saw nothing. Fix the page. What does it print then?

        <test-app>  <tea-order></tea-order></test-app><script type="module">  import "./tea-order.js";  import { seen } from "./test-app.js";  document.querySelector("tea-order").shadowRoot.querySelector("button").click();  console.log("The fake logger saw:", seen.join(", "));</script>
        ResultLoading…

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeKeep the subscription alive

          A hand-written tea-counter supports subscriptions. The first switch works, but the second doesn't. Fix the counter.js tab. What does the second press of Switch print?

          <tea-counter code="EUR">  <p><tea-price amount="4"></tea-price></p></tea-counter><button id="switch">Switch</button><script type="module">  import "./counter.js";  import "./tea-kit/index.js";  const counter = document.querySelector("tea-counter");  const price = document.querySelector("tea-price");  const codes = ["GBP", "JPY"];  document.querySelector("#switch").addEventListener("click", async () => {    counter.setCode(codes.shift() ?? "EUR");    await price.updateComplete;    console.log(price.textContent);  });</script>
          ResultLoading…

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeFind why the root never asks again

            This page has a root, and tea-front loads late. But the total never gets the currency. Fix the tea-total.js tab. What does the page print when you press Load tea-front?

            <tea-front>  <p><tea-total></tea-total></p></tea-front><button id="load">Load tea-front</button><script type="module">  import "./root.js";  import "./tea-total.js";  const total = document.querySelector("tea-total");  document.querySelector("#load").addEventListener("click", async () => {    await import("./tea-front.js");    await total.updateComplete;    console.log(total.textContent);  });</script>
            ResultLoading…

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              The context quiz · 7 questionsScore: first tries count
              1. Question 1 of 7Why must a context-request event be composed?

                Choose an answer to see the explanation.

              2. Question 2 of 7Oolong's card sits inside <tea-currency code="GBP">, which sits inside <tea-currency code="EUR">. What does its price show?

                Choose an answer to see the explanation.

              3. Question 3 of 7What does a provider do once it knows it can answer a request?

                Choose an answer to see the explanation.

              4. Question 4 of 7What does this code with three listeners print, line by line?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                const shop = new EventTarget();
                shop.addEventListener("context-request", (event) => event.callback("GBP"));
                shop.addEventListener("context-request", (event) => {
                  event.stopImmediatePropagation();
                  event.callback("EUR");
                });
                shop.addEventListener("context-request", (event) => event.callback("JPY"));
                
                const request = new Event("context-request");
                request.callback = (value) => console.log(value);
                shop.dispatchEvent(request);

                Choose an answer to see the explanation.

              5. Question 5 of 7A consumer asks with subscribe: false. Later, the provider's value changes. What does the consumer get?

                Choose an answer to see the explanation.

              6. Question 6 of 7A price connects before its provider is defined, and no root is attached. The provider is defined a moment later. What does the price get?

                Choose an answer to see the explanation.

              7. Question 7 of 7Why do Lit's docs give context an advantage over importing a shared logger module?

                Choose an answer to see the explanation.

              Key takeaways

              • Prop drilling makes every component in the middle carry a value it never uses.
              • A consumer fires a context-request event that bubbles and is composed, with a key and a callback.
              • The nearest provider of the key calls stopImmediatePropagation(), then the callback with its value.
              • Keys match with ===. Share one Symbol from one module.
              • A consumer asks in hostConnected() and unsubscribes in hostDisconnected(), so both sides fit as controllers.
              • With subscribe: true, the provider calls the callback for each new value, with the same unsubscribe function.
              • A provider defined after its consumers misses them. Define providers first, or attach a root.
              • The kit and @lit/context answer each other, because both follow the protocol.
              • Context can hand in services, like a logger. A test wraps the component in a provider with a fake.

              Remember the one-liner.
              Ask up, and the nearest provider answers: nothing in between has to carry it.

              Sources

              The facts on this page come from these specifications, docs, and source files:

              Support data comes from MDN's browser-compat-data. The composed flag is explained on MDN.

              Coming next: Async data in components. Load data in a component and show loading, error, and done states, and cancel what's stale.

              CompleteFrontend Clear concepts. Working examples.