Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 38 ยท Events and Slots

The Context Protocol and @lit/context

Share data with deeply nested Lit components without prop drilling. Learn how the context protocol works, then use createContext, ContextProvider and ContextConsumer.

Passing a value through five layers of components that do not care about it is called prop drilling. A theme, the signed-in user or a locale are needed by leaves deep in the tree, yet every layer between must pass them along. Context solves this: an ancestor provides a value and any descendant can consume it, whatever the depth.

Lit implements context with the Web Components Community Group's context protocol, which is plain DOM events. That means context works across frameworks, and the @lit/context package is only a convenient wrapper over it. This lesson first builds a tiny version by hand so that the mechanism is clear, then uses the real package.

How the protocol works

The idea fits on one slide.

Asking for context

Consumer Fires context-request
Event bubbles up bubbles + composed
Provider answers Calls the callback

No import links the two sides, only a shared key.

1 / 2
  1. A consumer dispatches a context-request event with a context key and a callback. The event is bubbles: true, composed: true.
  2. The nearest ancestor that provides that key calls event.stopPropagation() and invokes the callback with the current value.
  3. With subscribe: true, the provider keeps the callback and calls it again on each change.

A hand-written provider and consumer

Here is the whole mechanism in about twenty lines. This is a teaching stand-in that follows the protocol's shape; use @lit/context (below) in real code.

Context from scratch

Four layers deep, deep-label gets its value with no property passed through the middle. If it is placed outside any provider, nothing answers and it shows the fallback.

Using @lit/context

The official package wraps those events in a typed API: createContext makes a key, ContextProvider (a reactive controller) serves it, and ContextConsumer (also a controller) reads it.

ContextProvider and ContextConsumer

What to notice:

  • The context key should be unique: a Symbol, or a string you own. Two keys with the same value would collide.
  • ContextConsumer re-renders its host automatically because subscribe: true makes the provider push updates.
  • provider.setValue(...) updates all subscribers; assigning provider.value = ... also works.

Decorators with TypeScript

With TypeScript decorators the same code is shorter. This is shown read-only because decorators need a build step (see Tooling and Build Setup).

TypeScript
import { createContext, provide, consume } from "@lit/context";

export interface User { name: string; }
export const userContext = createContext<User>("user");

@customElement("app-root")
class AppRoot extends LitElement {
  @provide({ context: userContext })
  @property({ attribute: false })
  user: User = { name: "Ada" };
}

@customElement("user-name")
class UserName extends LitElement {
  @consume({ context: userContext, subscribe: true })
  @state()
  private user?: User;

  render() { return html`${this.user?.name}`; }
}

@provide serves the decorated property and updates subscribers whenever it changes; @consume injects the value and re-renders on change.

Provide objects, not constantly new objects

Because subscribers are notified on every setValue, avoid creating a fresh object every render of the provider. Keep one stable object (a store, a class instance) and mutate or replace it on purpose.

Context with a store object

When to use context (and when not)

Context is excellent for ambient, rarely changing data: theme, locale, the current user, a design-system configuration, a router or store instance. It is a poor fit for data that changes many times per second or for things that are really one component's local state.

  • Do use it to hand a store instance down, then subscribe to the store for fine-grained updates.
  • Do make the dependency explicit in documentation: a component that needs a context should say so.
  • Do not use it to avoid a one- or two-level property pass; plain properties are easier to trace.
  • Remember a consumer outside a provider gets undefined; give your UI a sensible fallback.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does a consumer ask a provider for a value in the context protocol?

    The request is a DOM event; the nearest provider with a matching key answers through the callback.
  2. 2. What does subscribe: true on a consumer do?

    With subscribe, the provider keeps the callback and re-invokes it on each change; the controller then re-renders the host.
  3. 3. Which is a good candidate for context?

    Context suits ambient values that many descendants read and that change rarely.
  4. 4. What does a consumer receive when no ancestor provides its context?

    No one answers the event, so the value stays undefined.

Summary

  • Context shares ambient data with any descendant, avoiding prop drilling.
  • It is built on a bubbling, composed context-request DOM event, so it works across shadow roots and frameworks.
  • @lit/context offers createContext, ContextProvider, ContextConsumer and the @provide/@consume decorators.
  • Use subscribe: true for live updates and provide stable objects, such as a store.
  • Keep local state local; use plain properties for short hops.

Next: Form-Associated Custom Elements