completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Signals in components

Learn how signals in web components work: build a signal, a computed, and an effect, tie effects to connectedCallback, and try the TC39 polyfill and Lit.

By the end, you can
  • 01
    Build signals yourselfWrite a state signal, a computed signal, and an effect in one small file, and say why a computed is lazy and cached.
  • 02
    Tie an effect to the elementStart an effect in connectedCallback() and stop it in disconnectedCallback(), so a removed element stops drawing.
  • 03
    Pick a signal libraryKnow what the TC39 proposal adds, run its polyfill, and use signals with Lit, Preact Signals, or alien-signals.

How do signals work in web components?

Meena is building the order page for Leaf and Kettle. A small badge in the header shows the cart's total. Far below, the checkout panel shows the same total.

Asha adds a cup of Oolong. Both numbers must change. In lesson 18.4, a Proxy store did this. But it asked every component to update on every write, even ones that don't show the total. Can each component update only when its own value changes?

Yes, with signals. A signal is a value that remembers who read it, and tells only them when it changes. A web component reads signals inside an effect: a function that runs again when a signal it read changes. It starts the effect in connectedCallback(), and stops it in disconnectedCallback().

Here is the whole idea. Press Add Oolong, then Add Sencha:

A header badge and a checkout panel that share one totalPop out in the code editor (opens in a new tab)HTML
<p>Leaf and Kettle <cart-badge></cart-badge></p><button id="oolong">Add Oolong</button><button id="sencha">Add Sencha</button><p><checkout-panel></checkout-panel></p><script type="module">  import "./cart-badge.js";  import "./checkout-panel.js";  import { addTea } from "./cart.js";  document.querySelector("#oolong").addEventListener("click", () => addTea("Oolong", 5));  document.querySelector("#sencha").addEventListener("click", () => addTea("Sencha", 4));</script>
ResultLoading…
  • Line 1 is the header badge, and line 4 is the checkout panel. Lines 6 and 7 load them from their tabs.
  • Lines 9 and 10 add a tea with addTea(), from the cart.js tab. Neither line names the badge or the panel.

As it loads, it prints The badge drew. Cart: 0 and The checkout drew. Total: 0. Add Oolong prints The badge drew. Cart: 5, then The checkout drew. Total: 5. Add Sencha prints both again, with 9.

Open the cart.js tab. Line 3 makes cart, a signal that holds a list of teas. Line 5 makes cartTotal, a signal worked out from the cart. Both components read cartTotal. Neither one subscribes by hand.

Real-life analogyThe chalkboard by the counter

At Leaf and Kettle, the day's price is on a chalkboard. Each waiter who copies it onto a menu signs a list under the board. When the manager changes the price, she reads the list and tells only those waiters. The cooks never read the board, so nobody bothers them.

In real life: The chalkboard with the day's price
In JavaScript: A signal, like cart
In real life: A waiter who copies the price, and signs the list
In JavaScript: An effect that calls get()
In real life: The manager changing the board
In JavaScript: cart.set()
In real life: Telling only the waiters on the list
In JavaScript: Running only the effects that read it
The main idea

A signal is a value that remembers who read it. Writing it tells only those readers. A component reads signals inside an effect, which runs again when they change. Start the effect when the element joins the page, and stop it when the element leaves.

You met a signal once before. In lesson 18.2, uhtml's signal() redrew a ticket by itself. Lesson 18.4 built a Proxy store, which asked every subscriber to update. This lesson builds signals by hand. Then it runs the proposal's polyfill, and three libraries.

What is a signal in JavaScript?

A signal is a box for one value, with a list of who read it. Lit's docs name the three parts that signal libraries have (Lit):

  • A state signal holds a value you set. cart is one. In our code, it's a State.
  • A computed signal works its value out from other signals. cartTotal is one. It's a Computed.
  • An effect is a function that runs again when a signal it read changes. The badge draws in one.

Two rules join them:

  • Reading tracks. When an effect or a computed calls get(), the signal adds it to its list of readers.
  • Writing notifies. When you call set(), the signal tells every reader on its list.

The proposal calls this automatic dependency tracking. A computed finds the signals it needs by itself (TC39). Nobody writes a subscribe call.

So a write reaches only the code that read that value. This page has the badge, and a board for today's special:

A badge and a board that read different signalsPop out in the code editor (opens in a new tab)HTML
<p><cart-badge></cart-badge></p><p><special-board></special-board></p><button id="add">Add Oolong</button><button id="special">Change the special</button><script type="module">  import "./cart-badge.js";  import "./special-board.js";  import { addTea } from "./cart.js";  import { special } from "./special.js";  document.querySelector("#add").addEventListener("click", () => addTea("Oolong", 5));  document.querySelector("#special").addEventListener("click", () => special.set("Assam"));</script>
ResultLoading…
  • Line 1 is the badge, which reads cartTotal. Line 2 is the board, from the special-board.js tab. Its effect reads special, from the special.js tab, and nothing else.
  • Line 10 writes the cart. Line 11 writes the special.

As it loads, both draw. Change the special prints only The board drew. Special: Assam. Add Oolong prints only The badge drew. Cart: 5. Press Change the special again, and nothing prints. Assam is already the special, and set() ignores a value that is the same.

Three columns. On the left, two state signals: cart and special. In the middle, a computed signal, cartTotal. On the right, three effects: the badge's, the checkout's, and the board's. Arrows go from cart to cartTotal, from cartTotal to the badge's and the checkout's effects, and from special to the board's effect.cartread bycartTotalbadge's effectcheckout's effectspecialboard's effectstatecomputedeffects
Each arrow goes from a signal to a reader that read it. A write to cart reaches cartTotal and its two effects. The board's effect read only special, so it never hears about the cart.

Lesson 18.4's store asked every host to update on every write, whatever it read. Here, each write finds its own readers. Why it matters: on a page with many components, a change wakes only the few that show it.

The JavaScript lesson on how signals track who reads them builds a tiny signal too. Next, we build one for components.

How do you build signals from scratch?

A signals library sounds big, but its core is small. Our signals.js is 83 lines, in four parts. You can open it as a tab in any page above. The first part is how a signal learns who read it:

signals.js: tracking who reads whatJavaScript
let running = null;

function track(signal) {
  if (!running) return;
  signal.readers.add(running);
  running.sources.add(signal);
}

function forget(reader) {
  for (const signal of reader.sources) signal.readers.delete(reader);
  reader.sources.clear();
}

function runTracked(reader, fn) {
  forget(reader);
  const outer = running;
  running = reader;
  try {
    return fn();
  } finally {
    running = outer;
  }
}
  • Line 1 is running: the reader that is running right now, or null. A reader is a computed or an effect.
  • Lines 3 to 7 are track(). A signal calls it inside get(). Line 5 adds the running reader to the signal's readers. Line 6 adds the signal to the reader's sources. Now each knows the other.
  • Lines 9 to 12 are forget(). They take a reader off every signal it read.
  • Lines 14 to 23 are runTracked(). Line 15 forgets the old sources, so the reader starts fresh. Line 17 makes it the running reader, and line 19 runs its function. Every get() inside calls track().
  • Line 21 puts the outer reader back, even if the function throws.

Line 21 lets readers nest. A computed can run inside an effect. While it runs, its reads belong to it. Then the effect is the running reader again.

Real-life analogyThe library writes it down twice

When you borrow a book, the library writes it down twice. Your name goes on the book's slip. The book goes on your card. When a new edition comes in, the library reads the slip and calls you. When you leave, your card shows every slip to clear.

In real life: A book
In JavaScript: A signal
In real life: The person at the desk
In JavaScript: The running reader
In real life: Your name on the book's slip
In JavaScript: The signal's readers
In real life: The book on your card
In JavaScript: The reader's sources

The second part is the state signal:

signals.js: a state signalJavaScript
export class State {
  readers = new Set();
  #value;
  constructor(value) {
    this.#value = value;
  }
  get() {
    track(this);
    return this.#value;
  }
  set(value) {
    if (Object.is(value, this.#value)) return;
    this.#value = value;
    for (const reader of this.readers) reader.stale();
  }
}
  • Line 2 is the readers, in a Set. A Set keeps each reader once, however often it reads.
  • Lines 7 to 10 are get(). Line 8 records the reader. Line 9 returns the value.
  • Lines 11 to 15 are set(). Line 12 stops when the new value is the same, by Object.is(). Line 14 calls stale() on every reader. Stale means out of date.

The fourth part is the effect. (The third, the computed, has its own section next.)

signals.js: an effect that runs once per batchJavaScript
export function effect(fn) {
  let queued = false;
  let stopped = false;
  const reader = { sources: new Set(), stale };
  function stale() {
    if (queued) return;
    queued = true;
    queueMicrotask(() => {
      queued = false;
      if (!stopped) runTracked(reader, fn);
    });
  }
  runTracked(reader, fn);
  return () => {
    stopped = true;
    forget(reader);
  };
}
  • Lines 2 and 3 are two flags. queued says a run is already waiting. stopped says the effect is over.
  • Line 4 is the effect's reader: its sources, and its stale(), which a signal calls on a write.
  • Lines 5 to 12 are stale(). It doesn't run the function. Line 8 queues a microtask, once. Line 10 runs the function there, tracked again, unless it was stopped.
  • Line 13 runs the function the first time, at once.
  • Lines 14 to 17 return the stop function. It sets stopped, and forget() takes the effect off every signal.

Why a microtask? Lesson 18.1 batched updates the same way. Many writes in one click wake the effect many times. It runs once, after they're all done, before the browser paints.

This isn't only a teaching trick. FAST, Microsoft's web component library, used the same idea before the proposal. Its observable.ts keeps one module variable, watcher (line 171). Reading an observable property tells that watcher (lines 202 to 207). observe() sets the watcher, runs the expression, and puts the old one back in a finally (lines 277 to 292). Nolan Lawson's small framework starts with a currentEffect variable too (his post).

Why is a computed signal lazy and cached?

A computed signal works its value out from other signals, as cartTotal does from cart. The proposal asks two things of it (TC39):

  • Lazy: it works its value out only when someone reads it.
  • Cached: it keeps that value until a signal it read changes.

Here is the third part of signals.js:

signals.js: a computed signalJavaScript
export class Computed {
  readers = new Set();
  sources = new Set();
  #fn;
  #value;
  #fresh = false;
  constructor(fn) {
    this.#fn = fn;
  }
  get() {
    track(this);
    if (!this.#fresh) {
      this.#value = runTracked(this, this.#fn);
      this.#fresh = true;
    }
    return this.#value;
  }
  stale() {
    if (!this.#fresh) return;
    this.#fresh = false;
    for (const reader of this.readers) reader.stale();
  }
}
  • Line 6 is #fresh. It says whether the kept value is still good. It starts as false.
  • Lines 10 to 17 are get(). Line 11 records whoever reads the computed. Lines 12 to 15 run the function only when the value isn't fresh. Line 13 runs it tracked, so the computed learns its own sources.
  • Lines 18 to 22 are stale(). A source calls it on a write. Line 20 marks the value old. Line 21 passes the news on to the computed's own readers. Line 19 stops when it's already stale, so the news passes once.

stale() never runs the function. Count the runs:

A computed that counts its own runsPop out in the code editor (opens in a new tab)HTML
<script type="module">  import { State, Computed } from "./signals.js";  const cups = new State(2);  let runs = 0;  const total = new Computed(() => {    runs += 1;    return cups.get() * 4;  });  console.log(`Runs before any read: ${runs}`);  console.log(`Total: ${total.get()}, runs: ${runs}`);  console.log(`Total: ${total.get()}, runs: ${runs}`);  cups.set(3);  console.log(`After a write, runs: ${runs}`);  console.log(`Total: ${total.get()}, runs: ${runs}`);</script>
ResultLoading…
  • Lines 5 to 8 make total, and count each run in runs.
  • Line 9 prints before any read. Lines 10 and 11 read twice.
  • Line 12 writes. Line 13 prints after the write, and line 14 reads again.

It prints Runs before any read: 0. Then Total: 8, runs: 1, twice. Then After a write, runs: 1, and Total: 12, runs: 2.

Four rows, from the counts page. First, total.get() runs the function cups.get() * 4 and gives 8: runs 1. Second, total.get() gives the 8 it kept, without running the function: runs 1. Third, cups.set(3) only marks total stale: runs 1. Fourth, total.get() runs the function again and gives 12: runs 2.total.get()cups.get() * 48runs: 1total.get()the value it kept8runs: 1cups.set(3)total is staleruns: 1total.get()cups.get() * 412runs: 2
A computed runs its function only when someone reads it while it's stale. The second read and the write run nothing, so runs goes from 1 to 2 only on the last read.
Real-life analogyThe bill is added up when you ask

A waiter doesn't add up the bill after every dish. She adds it up when the guests ask, and writes the sum down. If they ask again before ordering more, she reads the same sum. A new dish makes the sum old, but she still waits until they ask.

In real life: The sum on the bill
In JavaScript: The computed's kept value
In real life: Adding it up
In JavaScript: Running the computed's function
In real life: The guests asking for the bill
In JavaScript: get()
In real life: A new dish on the table
In JavaScript: A write that makes it stale

Why it matters: in the overview, two components read cartTotal. Each Add ran its reduce() once. The second reader got the kept value.

What is the TC39 signals proposal?

TC39 is the committee that adds features to JavaScript. A proposal moves through numbered stages. Signals are at Stage 1 (TC39). At Stage 1, the committee has agreed to explore the problem. Upcoming JavaScript features explains the stages.

So signals are not part of JavaScript. Ask the browser:

Is there a Signal in the browser?Pop out in the code editor (opens in a new tab)JavaScript
console.log(typeof Signal);

Line 1 asks what kind of thing Signal is. Chrome prints undefined. No browser ships signals, and MDN's compatibility data has no entry for them. To try the proposal, you load signal-polyfill. A polyfill is code that adds a missing feature, written in plain JavaScript.

Why make it a standard? Today each framework has its own signals, and they can't see each other's. The README's first reason is interoperability: signals from one library would work with any other. Its authors compare it to Promises/A+, which came before promises were built in. People from Angular, FAST, Preact, Solid, Svelte, Vue, and more gave input (TC39).

Real-life analogyOne plug for every socket

Countries use different plugs, so a traveller carries an adapter. If every country agreed on one plug shape, any kettle would work in any socket. Until then, the adapter does the job.

In real life: Each country's own plug
In JavaScript: Each library's own signals
In real life: One shared plug shape
In JavaScript: The proposal's Signal API
In real life: The travel adapter
In JavaScript: The polyfill
In real life: Any kettle in any socket
In JavaScript: Components from different libraries sharing one signal

The proposal has three parts:

  • Signal.State: a state signal, with get() and set().
  • Signal.Computed: a computed signal, lazy and cached, with get().
  • Signal.subtle.Watcher: it tells a library that a signal it watches may have changed. subtle marks parts meant for library authors.

There is no effect. The README says effect timing ties into each framework's rendering, so it leaves effects to libraries (TC39).

A crate labelled the proposal holds three cards: Signal.State, Signal.Computed, and Signal.subtle.Watcher. Outside it, on the right, a shaded card, effect(), marked a library builds it. An arrow goes from the Watcher to effect().Signal.StateSignal.ComputedSignal.subtle.Watcherthe proposaleffect()a library builds it
The proposal has three parts. effect() isn't one of them: each library builds its own on a Watcher, as signals.js on the polyfill does.

Our signals.js already uses the proposal's names. So here it is again, on the polyfill:

signals.js on the TC39 polyfillJavaScript
import { Signal } from "https://esm.sh/signal-polyfill@0.2.3";

export const State = Signal.State;
export const Computed = Signal.Computed;

export function effect(fn) {
  let stopped = false;
  const runner = new Signal.Computed(fn);
  const watcher = new Signal.subtle.Watcher(() => {
    queueMicrotask(() => {
      if (stopped) return;
      runner.get();
      watcher.watch();
    });
  });
  watcher.watch(runner);
  runner.get();
  return () => {
    stopped = true;
    watcher.unwatch(runner);
  };
}
  • Line 1 loads the polyfill from esm.sh, at a pinned version.
  • Lines 3 and 4 hand out the polyfill's own State and Computed. cart.js doesn't change.
  • Line 8 wraps the effect's function in a Computed, called runner.
  • Lines 9 to 15 make a Watcher. The proposal doesn't let its callback read or write signals, so it only queues a microtask.
  • In that microtask, line 12 runs the function again if a source changed. Line 13 asks the watcher to call back on the next change.
  • Line 16 watches the runner, and line 17 runs it the first time.
  • Lines 18 to 21 return the stop function. unwatch() lets the polyfill let go of the runner.

Now run one page on both. Press Add Oolong, then Swap Oolong for Assam. Assam costs 5 too, so the total doesn't change:

Playground: our signals.js and the TC39 polyfill
A badge, and a swap that keeps the totalPop out in the code editor (opens in a new tab)HTML
<p><cart-badge></cart-badge></p><button id="add">Add Oolong</button><button id="swap">Swap Oolong for Assam</button><script type="module">  import "./cart-badge.js";  import { cart, addTea } from "./cart.js";  document.querySelector("#add").addEventListener("click", () => addTea("Oolong", 5));  document.querySelector("#swap").addEventListener("click", () => {    cart.set(cart.get().map((tea) => (tea.name === "Oolong" ? { name: "Assam", price: 5 } : tea)));  });</script>
ResultLoading…
Try it yourself
The effect runs again

The swap writes a new cart, so cartTotal goes stale and the badge's effect runs again. It works the total out, gets 5 again, and draws the same thing.

Only the signals.js tab changes. Press Add Oolong, then Swap Oolong for Assam.
  • Line 7 adds Oolong. Line 9 swaps it for Assam: a new list, with the same total.

Both print 0, then 5. On the swap, our signals.js prints The badge drew. Cart: 5 again. The polyfill prints nothing.

The polyfill works cartTotal out again, sees 5, and stops there. The README calls this glitch-free: no work that isn't needed. Our 83 lines skip that check. On the counts page, the polyfill prints the same five lines: its Computed is lazy and cached too.

Two warnings from Lit's docs. The proposal and its polyfill can still change. And a page must load only one copy of the polyfill. Two copies split the signals into two groups that can't see each other (Lit).

How do you stop an effect when a component is removed?

Look again at the badge's tab:

cart-badge.js: start in connectedCallback, stop in disconnectedCallbackJavaScript
  connectedCallback() {
    this.#stop = effect(() => {
      const total = cartTotal.get();
      this.textContent = `Cart: ${total}`;
      console.log(`The badge drew. Cart: ${total}`);
    });
  }

  disconnectedCallback() {
    this.#stop();
  }
  • Lines 1 to 7: connectedCallback() starts the effect, and keeps its stop function in #stop.
  • Lines 9 to 11: disconnectedCallback() calls it.

Lesson 3.3 cleaned up timers and listeners the same way. An effect needs it too. Press Add Oolong, Remove the badge, then Add Oolong again:

Playground: a badge that stops, and one that doesn't
A badge, and a button that removes itPop out in the code editor (opens in a new tab)HTML
<p>Header: <cart-badge></cart-badge></p><button id="add">Add Oolong</button><button id="remove">Remove the badge</button><script type="module">  import "./cart-badge.js";  import { addTea } from "./cart.js";  const badge = document.querySelector("cart-badge");  document.querySelector("#add").addEventListener("click", () => addTea("Oolong", 5));  document.querySelector("#remove").addEventListener("click", () => badge.remove());</script>
ResultLoading…
Try it yourself
The removed badge goes quiet

Removing the badge runs disconnectedCallback(), which stops the effect. The second Add changes the cart, and nobody draws.

Only the cart-badge.js tab changes. Press Add Oolong, Remove the badge, then Add Oolong.
  • Line 7 keeps the badge in a variable. Line 9 removes it from the page.
  • In the cart-badge.js tab, line 11 prints whether the badge is on the page, with isConnected.

Both print The badge drew. Cart: 0. On the page: true, then the same with 5. After the removal, the badge that stops prints nothing. The one that never stops prints The badge drew. Cart: 10. On the page: false.

Two halves, after the badge is removed. Left, labelled stopped: a card, cartTotal, and below it a crossed-out card, badge's effect, with no arrow between them, marked nothing runs. Right, labelled never stopped: an arrow from cartTotal to the badge's effect, marked still a reader and still runs off the page.stoppedcartTotalbadge's effectnothing runsnever stoppedcartTotalstill a readerbadge's effectstill runs off the page
Stopped, the effect is off cartTotal's list of readers, and nothing runs. Never stopped, it stays on the list: the badge draws off the page, and can't be freed.

The removed badge drew where nobody can see it. That's wasted work, and it holds memory too. cartTotal keeps the effect in its readers, and the effect's function holds the badge. So the badge can't be freed while the cart lives. The proposal's README warns the same about its Watcher: call unwatch() to clean up effects (TC39).

Real-life analogyA newspaper for an empty house

When a family moves out, they cancel the newspaper. If they forget, it still comes every morning, and piles up at an empty door. If they move back, they order it again.

In real life: Moving in, and ordering the paper
In JavaScript: connectedCallback() starting the effect
In real life: The paper each morning
In JavaScript: The effect running after each write
In real life: Cancelling it when you move out
In JavaScript: Calling #stop() in disconnectedCallback()
In real life: Papers piling up at an empty house
In JavaScript: A removed badge that still draws

Moving an element runs both callbacks, as lesson 3.3 showed. So a moved badge stops its effect and starts a new one, which draws at once. Exercise 2 moves a badge that never stops.

Lit's SignalWatcher does this for you (Lit). Its source shows how (lines 293 to 321):

  • Its disconnectedCallback() stops watching in a microtask, if the element is still off the page. So a move in one task keeps watching.
  • Its connectedCallback() asks for a full update, because the element may have missed changes while it was away.

How do signals work with reactive properties?

The badge above writes its own textContent. The kit's components draw with ReactiveTea instead, from lesson 18.1. A setter asks for an update, and ReactiveTea draws once per batch. How do signals fit in?

Justin Fagnani explains Lit's answer. Its signals helper watches the update, and calls requestUpdate() when a signal it read changes (his post). Ours can be smaller. The effect copies cartTotal into one of the badge's own properties:

cart-badge.js on ReactiveTea: an effect sets a propertyJavaScript
  connectedCallback() {
    this.#stop = effect(() => {
      this.total = cartTotal.get();
      console.log(`The effect ran. Cart: ${this.#total}`);
    });
    this.requestUpdate();
  }

  disconnectedCallback() {
    this.#stop();
  }

  update() {
    render(html`Cart: ${this.#total}`, this);
    console.log(`The badge drew. Cart: ${this.#total}`);
  }
  • Lines 2 to 5 are the effect. Line 3 reads cartTotal and sets the badge's total property. Its setter, in the tab, calls requestUpdate("total", oldValue).
  • Line 6 asks for the first drawing. The first total is 0, the same as the start, so the setter doesn't ask.
  • Lines 13 to 16 are update(). Line 14 draws with html.js, from lesson 18.2.

Press Add Oolong and Sencha, then Swap Oolong for Assam:

Two writes in one click, and a swap that keeps the totalPop out in the code editor (opens in a new tab)HTML
<p>Header: <cart-badge></cart-badge></p><button id="add">Add Oolong and Sencha</button><button id="swap">Swap Oolong for Assam</button><script type="module">  import "./cart-badge.js";  import { cart, addTea } from "./cart.js";  document.querySelector("#add").addEventListener("click", () => {    addTea("Oolong", 5);    addTea("Sencha", 4);  });  document.querySelector("#swap").addEventListener("click", () => {    cart.set(cart.get().map((tea) => (tea.name === "Oolong" ? { name: "Assam", price: 5 } : tea)));  });</script>
ResultLoading…
  • Lines 7 to 10 write the cart twice in one click.
  • Lines 11 to 13 swap a tea, and keep the total.

As it loads, it prints The effect ran. Cart: 0, then The badge drew. Cart: 0. The click prints The effect ran. Cart: 9, then The badge drew. Cart: 9: two writes, one run, one drawing. The swap prints only The effect ran. Cart: 9.

Two layers skip work here. signals.js joins the two writes into one run. Then ReactiveTea's hasChanged() sees that 9 is still 9, and draws nothing (lesson 18.1). Why it matters: the badge keeps everything ReactiveTea gives it, like batching and updateComplete.

Should a component use signals or properties?

Use both, for different jobs. Lit's docs call signals useful for shared observable state: state that many components read and change (Lit). Lit still keeps reactive properties on each element. Fagnani explains why. A Lit element controls only its own API. Its properties see only changes made on the element itself, and it doesn't dictate what kind of data you use (his post).

  • A property is like a name card on one seat. The host decides what it says.
  • A signal is like the price board. Everyone in the shop reads the same one.

Here is how the two compare. Read each row across:

Properties and signals
What you askA propertyA signal
Who sets it?Whoever uses the component: its parent, the page, or a framework.Any code that imports it.
How far does it reach?One element.Every reader, anywhere on the page.
How does the component hear about a change?Its setter runs and asks for an update.An effect that read it runs again.
Can React or plain HTML set it?Yes. React 19 sets a property, and an attribute can mirror one.No. Code has to import the signal.
What is it good for?A component's inputs, like a tile's tea.State that many components share, like the cart.

So the tea a shelf passes its tile stays a property, as in lesson 18.4. The cart, which a header and a checkout far apart both show, is a signal. The state management lesson calls that one place the single source of truth.

A reusable component can stay free of signals. Give it a property or some text, and let the page connect a signal to it with an effect. The kit does that at the end of this lesson.

Which signal libraries work with web components?

Any library whose effects you can start and stop. A custom element has the two callbacks to do it in. Here is the same badge on four of them. Press Add Oolong and Sencha. One click writes the cart twice:

Playground: one badge on four signal libraries
A badge, and one click that writes the cart twicePop out in the code editor (opens in a new tab)HTML
<p>Header: <cart-badge></cart-badge></p><button>Add Oolong and Sencha</button><script type="module">  import { State, Computed, effect } from "./signals.js";  const cart = new State([]);  const cartTotal = new Computed(() => cart.get().reduce((total, tea) => total + tea.price, 0));  class CartBadge extends HTMLElement {    #stop;    connectedCallback() {      this.#stop = effect(() => {        this.textContent = `Cart: ${cartTotal.get()}`;        console.log(`The badge drew. Cart: ${cartTotal.get()}`);      });    }    disconnectedCallback() {      this.#stop();    }  }  customElements.define("cart-badge", CartBadge);  document.querySelector("button").addEventListener("click", () => {    cart.set([...cart.get(), { name: "Oolong", price: 5 }]);    cart.set([...cart.get(), { name: "Sencha", price: 4 }]);  });</script>
ResultLoading…
Try it yourself
One run per batch

Both writes happen before the microtask, so the effect runs once, with 9.

Each choice is the same badge, written with a different library. Press Add Oolong and Sencha.
  • Line 4 loads the library: from the signals.js tab, or from esm.sh at a pinned version. Lit's page loads its signals package on line 5.
  • The rest is the same badge, in each library's own words for reading and writing.

Our signals.js and Lit print 0, then 9: one drawing for both writes. Preact Signals and alien-signals print 0, 5, then 9. They run the effect right after each write.

Here is how each one reads, writes, and runs effects. Read each row across:

Four signal libraries and the polyfill
LibraryHow do you read?How do you write?When does an effect run again?
Our signals.jscart.get()cart.set(value)Once, in a microtask after the writes.
The TC39 polyfillcart.get()cart.set(value)It has no effect. A library builds one on a Watcher.
Preact Signalscart.valuecart.value = valueRight after each write, unless the writes are inside batch().
alien-signalscart()cart(value)Right after each write, unless the writes sit between startBatch() and endBatch().
Lit's @lit-labs/signalscart.get()cart.set(value)In the element's next update, once for all the writes before it.

Lit's signals package

@lit-labs/signals brings the TC39 polyfill with it (Lit). SignalWatcher is a mixin: a function that takes a class and returns a new class that extends it. Any signal that render() reads is watched, and a change asks for one update. It's a Labs package, which means experimental. Lit's first signals package, @lit-labs/preact-signals, came with Lit 3.0 (Lit). Stage 8 has a whole lesson on signals in Lit.

Preact Signals

@preact/signals-core is the core of Preact Signals (Preact). It needs no Preact: the badge above loads it alone. It has signal(), computed(), effect(), and batch(). You read and write .value. effect() returns a function that stops it, so it fits the same two callbacks. batch() joins writes into one run, as exercise 6 shows.

alien-signals

alien-signals is a signals library built for speed. Its core was ported into Vue 3.6 (alien-signals). A signal is a function: cart() reads it, and cart(value) writes it. uhtml, from lesson 18.2, takes its signal() from @webreflection/alien-signals, a version of alien-signals that reads and writes .value (uhtml). That's the signal the ticket used.

Which to pick? For Lit components, @lit-labs/signals. For plain custom elements, any of them, as long as disconnectedCallback() stops the effects. And if the proposal lands, libraries built on it will share one set of signals (Fagnani).

Adding signals to the tea kit

The kit gets signals in kitAfter185:

  • tea-kit/signals.js (new helper): State, Computed, and effect(). It's the file this lesson built, with comments.
  • tea-kit/custom-elements.json: the new module.

The kit's components stay as they were. A kit tea-badge knows nothing about signals, so the page connects one with an effect. Press Add on Sencha, then + and Add on Oolong:

The kit's cards and badge, joined by signalsPop out in the code editor (opens in a new tab)HTML
<link rel="stylesheet" href="tea-kit/tokens.css"><p>Your order <tea-badge></tea-badge></p><tea-card name="Sencha" price="4"></tea-card><tea-card name="Oolong" price="5"></tea-card><p><checkout-panel></checkout-panel></p><script type="module">  import "./tea-kit/index.js";  import { effect } from "./tea-kit/signals.js";  import "./checkout-panel.js";  import { cart, addTea } from "./cart.js";  const badge = document.querySelector("tea-badge");  effect(() => {    const cups = cart.get().length;    badge.textContent = `${cups} ${cups === 1 ? "cup" : "cups"}`;  });  document.addEventListener("tea-add", (event) => {    const price = Number(event.target.getAttribute("price"));    for (let cup = 0; cup < event.quantity; cup++) addTea(event.tea, price);  });</script>
ResultLoading…
  • Line 8 imports effect() from the kit. In the cart.js and checkout-panel.js tabs, the import moves to the kit too.
  • Lines 12 to 15 are the page's effect. It reads the cart and writes the badge's text.
  • Lines 16 to 19 hear each card's tea-add. Line 18 adds one tea per cup.

The badge says 1 cup, then 3 cups. The checkout prints The checkout drew. Total: 4, then The checkout drew. Total: 14: two writes for Oolong's two cups, and one drawing.

The page's effect never stops, because the page lasts as long as its badge. A component's own effect is different: it starts and stops with the element.

Common mix-ups

  • "Signals are built into JavaScript now." No. The TC39 proposal is at Stage 1. You load its polyfill or a library.
  • "The proposal includes an effect() function." No. It has State, Computed, and a Watcher. Libraries build effects.
  • "A computed runs every time a signal it read changes." No. It's lazy. It runs only when someone reads it while it's stale.
  • "Removing an element stops its effects." No. Only your disconnectedCallback() stops them. Without it, the removed element keeps drawing.
  • "Reading a signal anywhere subscribes to it." No. Only a read inside an effect or a computed is tracked. Exercise 5 has a read outside one.
  • "Signals replace component properties." No. Properties stay a component's inputs. Signals hold state that many components share.
  • "Every signal library runs effects at the same moment." No. Preact Signals and alien-signals run them after each write. Our signals.js and Lit wait for one batch.
  • "Two copies of the polyfill work together." No. Lit's docs warn that two copies split the signals into groups that can't see each other.

Practice exercises

Exercise 1 · Warm-upCount a computed's runs

Predict what the page prints, then run it.

<script type="module">  import { State, Computed } from "./signals.js";  const cups = new State(3);  let runs = 0;  const total = new Computed(() => {    runs += 1;    return cups.get() * 4;  });  total.get();  cups.set(3);  total.get();  cups.set(5);  cups.set(6);  total.get();  console.log(`Runs: ${runs}`);</script>
ResultLoading…

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

    Exercise 2 · Warm-upMove a badge that never stops

    Press Move the badge, then Add Oolong. How many lines say Cart: 5?

    <p>Header: <cart-badge></cart-badge></p><button id="add">Add Oolong</button><button id="move">Move the badge</button><footer>Footer: </footer><script type="module">  import "./cart-badge.js";  import { addTea } from "./cart.js";  const badge = document.querySelector("cart-badge");  document.querySelector("#add").addEventListener("click", () => addTea("Oolong", 5));  document.querySelector("#move").addEventListener("click", () => document.querySelector("footer").append(badge));</script>
    ResultLoading…

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

      Exercise 3 · PracticeStop the badge's effect

      Press Add Oolong, Remove the badge, then Add Oolong. The removed badge still draws. Fix the cart-badge.js tab. How many lines does the page print in all then?

      <p>Header: <cart-badge></cart-badge></p><button id="add">Add Oolong</button><button id="remove">Remove the badge</button><script type="module">  import "./cart-badge.js";  import { addTea } from "./cart.js";  const badge = document.querySelector("cart-badge");  document.querySelector("#add").addEventListener("click", () => addTea("Oolong", 5));  document.querySelector("#remove").addEventListener("click", () => badge.remove());</script>
      ResultLoading…

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

        Exercise 4 · PracticeCount the teas in the checkout

        Make the checkout show how many teas are in the cart, with a new computed signal. What does it print after Add Oolong, then Add Sencha?

        <p>Leaf and Kettle <cart-badge></cart-badge></p><button id="oolong">Add Oolong</button><button id="sencha">Add Sencha</button><p><checkout-panel></checkout-panel></p><script type="module">  import "./cart-badge.js";  import "./checkout-panel.js";  import { addTea } from "./cart.js";  document.querySelector("#oolong").addEventListener("click", () => addTea("Oolong", 5));  document.querySelector("#sencha").addEventListener("click", () => addTea("Sencha", 4));</script>
        ResultLoading…

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

          Exercise 5 · ChallengeThe board that never changes

          Press Change the special. The board stays on Oolong. Fix the special-board.js tab. What does it print then?

          <p><cart-badge></cart-badge></p><p><special-board></special-board></p><button id="add">Add Oolong</button><button id="special">Change the special</button><script type="module">  import "./cart-badge.js";  import "./special-board.js";  import { addTea } from "./cart.js";  import { special } from "./special.js";  document.querySelector("#add").addEventListener("click", () => addTea("Oolong", 5));  document.querySelector("#special").addEventListener("click", () => special.set("Assam"));</script>
          ResultLoading…

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

            Exercise 6 · ChallengeBatch Preact's writes

            This is the Preact badge from the playground. Make one click draw once. What does the click print then?

            <p>Header: <cart-badge></cart-badge></p><button>Add Oolong and Sencha</button><script type="module">  import { signal, computed, effect } from "https://esm.sh/@preact/signals-core@1.14.5";  const cart = signal([]);  const cartTotal = computed(() => cart.value.reduce((total, tea) => total + tea.price, 0));  class CartBadge extends HTMLElement {    #stop;    connectedCallback() {      this.#stop = effect(() => {        this.textContent = `Cart: ${cartTotal.value}`;        console.log(`The badge drew. Cart: ${cartTotal.value}`);      });    }    disconnectedCallback() {      this.#stop();    }  }  customElements.define("cart-badge", CartBadge);  document.querySelector("button").addEventListener("click", () => {    cart.value = [...cart.value, { name: "Oolong", price: 5 }];    cart.value = [...cart.value, { name: "Sencha", price: 4 }];  });</script>
            ResultLoading…

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

              Check your understanding

              The signals quiz · 7 questionsScore: first tries count
              1. Question 1 of 7Nobody has read this computed signal yet. What does the last line print?

                Read the code, then predictJavaScript
                const cups = new State(2);
                let runs = 0;
                const total = new Computed(() => {
                  runs += 1;
                  return cups.get() * 4;
                });
                cups.set(3);
                console.log(runs);

                Choose an answer to see the explanation.

              2. Question 2 of 7What does the TC39 signals proposal give you?

                Choose an answer to see the explanation.

              3. Question 3 of 7Are signals built into JavaScript in today's browsers?

                Choose an answer to see the explanation.

              4. Question 4 of 7A badge starts its effect in connectedCallback() and has no disconnectedCallback(). After it's removed, the cart changes. What happens?

                Choose an answer to see the explanation.

              5. Question 5 of 7The ReactiveTea badge shows Cart: 9. You swap Oolong for Assam, at the same price. What does the page print?

                Choose an answer to see the explanation.

              6. Question 6 of 7With Preact Signals, what does this code print?

                Read the code, then predictJavaScript
                const cart = signal([]);
                effect(() => console.log(cart.value.length));
                cart.value = [...cart.value, "Oolong"];
                cart.value = [...cart.value, "Sencha"];

                Choose an answer to see the explanation.

              7. Question 7 of 7A shelf gives each tile its tea. Should the tile get the tea from a property or from a shared signal?

                Choose an answer to see the explanation.

              Key takeaways

              • A signal is a value that remembers who read it. Reading tracks, and writing tells only those readers.
              • A state signal holds a value. A computed works one out, only when read, and keeps it until a source changes.
              • An effect runs again when a signal it read changes. Ours runs once per batch, in a microtask.
              • The TC39 proposal is at Stage 1. It has State, Computed, and a Watcher, and leaves effects to libraries.
              • Start a component's effect in connectedCallback() and stop it in disconnectedCallback().
              • An effect that never stops keeps a removed element drawing, and in memory.
              • Use properties for a component's inputs, and signals for state many components share.
              • Lit's SignalWatcher, Preact Signals, and alien-signals all work with custom elements.

              Remember the one-liner.
              A signal tells only its readers when it changes, so start each effect when the element joins the page, and stop it when it leaves.

              Sources

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

              Support data comes from MDN's browser-compat-data.

              Coming next: A component base class. It pulls the code every component repeats into one class of helpers.

              CompleteFrontend Clear concepts. Working examples.