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.
- 01Build signals yourselfWrite a state signal, a computed signal, and an effect in one small file, and say why a computed is lazy and cached.
- 02Tie an effect to the elementStart an effect in
connectedCallback()and stop it indisconnectedCallback(), so a removed element stops drawing. - 03Pick 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:
<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>- 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.
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
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.
cartis one. In our code, it's aState. - A computed signal works its value out from other signals.
cartTotalis one. It's aComputed. - 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:
<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>- Line 1 is the badge, which reads
cartTotal. Line 2 is the board, from the special-board.js tab. Its effect readsspecial, 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.
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:
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, ornull. A reader is a computed or an effect. - Lines 3 to 7 are
track(). A signal calls it insideget(). 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. Everyget()inside callstrack(). - 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.
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:
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, byObject.is(). Line 14 callsstale()on every reader. Stale means out of date.
The fourth part is the effect. (The third, the computed, has its own section next.)
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.
queuedsays a run is already waiting.stoppedsays 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, andforget()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:
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 asfalse. - 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:
<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>- Lines 5 to 8 make
total, and count each run inruns. - 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.
runs goes from 1 to 2 only on the last read.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:
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).
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, withget()andset().Signal.Computed: a computed signal, lazy and cached, withget().Signal.subtle.Watcher: it tells a library that a signal it watches may have changed.subtlemarks 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).
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:
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
StateandComputed. cart.js doesn't change. - Line 8 wraps the effect's function in a
Computed, calledrunner. - 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:
<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>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.
- 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:
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:
<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>Removing the badge runs disconnectedCallback(), which stops the effect. The second Add changes the cart, and nobody draws.
- 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.
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).
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:
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
cartTotaland sets the badge'stotalproperty. Its setter, in the tab, callsrequestUpdate("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:
<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>- 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:
| What you ask | A property | A 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:
<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>Both writes happen before the microtask, so the effect runs once, with 9.
- 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:
| Library | How do you read? | How do you write? | When does an effect run again? |
|---|---|---|---|
| Our signals.js | cart.get() | cart.set(value) | Once, in a microtask after the writes. |
| The TC39 polyfill | cart.get() | cart.set(value) | It has no effect. A library builds one on a Watcher. |
| Preact Signals | cart.value | cart.value = value | Right after each write, unless the writes are inside batch(). |
| alien-signals | cart() | cart(value) | Right after each write, unless the writes sit between startBatch() and endBatch(). |
Lit's @lit-labs/signals | cart.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, andeffect(). 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:
<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>- 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
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><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>It prints Runs: 2. Line 9 runs it once. Line 10 sets the same value, so nothing goes stale, and line 11 gets the kept value. Lines 12 and 13 make it stale, and line 14 runs it once more.
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><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>Two lines say Cart: 5. The move started a second effect, and nothing stopped the first. Both read cartTotal, so Add Oolong runs both.
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><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>Only the cart-badge.js tab changes: it gets a disconnectedCallback() that calls this.#stop(). Removing the badge stops its effect, so the second Add prints nothing. The page prints 2 lines in all.
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><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>Two tabs change. cart.js gets cartCount, a computed of the cart's length. checkout-panel.js reads it in its effect, so the effect now has two sources. After Oolong and Sencha it prints The checkout drew. Teas: 2, total: 9.
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><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>Only the special-board.js tab changes: the effect calls special.get() itself. Now the read is tracked, so the write runs the effect, and it prints The board drew. Special: Assam.
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><p>Header: <cart-badge></cart-badge></p><button>Add Oolong and Sencha</button><script type="module"> import { signal, computed, effect, batch } 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", () => { batch(() => { cart.value = [...cart.value, { name: "Oolong", price: 5 }]; cart.value = [...cart.value, { name: "Sencha", price: 4 }]; }); });</script>Line 4 imports batch, and the click wraps both writes in batch(). Preact runs the effect once, after the function returns, so the click prints only The badge drew. Cart: 9.
Check your understanding
Question 1 of 7Nobody has read this computed signal yet. What does the last line print?
Read the code, then predictJavaScriptconst 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.
Question 2 of 7What does the TC39 signals proposal give you?
Choose an answer to see the explanation.
Question 3 of 7Are signals built into JavaScript in today's browsers?
Choose an answer to see the explanation.
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.
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.
Question 6 of 7With Preact Signals, what does this code print?
Read the code, then predictJavaScriptconst 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.
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:
- JavaScript Signals standard proposal, TC39.
- Signals, Lit.
- Let's learn how modern JavaScript frameworks work by building one, Nolan Lawson.
- observable.ts, at fast-element 3.1.2, FAST.
- Stage 1 proposals, TC39.
- signal-polyfill, The Signals proposal's champions.
- signal-watcher.ts, at @lit-labs/signals 0.3.0, Lit.
- Reactive State with Signals in Lit, Justin Fagnani.
- React v19: support for custom elements, React.
- Bringing Signals to Lit Labs, Lit.
- Lit Launch Day: Lit 3.0, Labs graduations, a compiler and more, Lit.
- Signals: @preact/signals-core, Preact.
- alien-signals, Johnson Chu.
- uhtml 5.0.9: src/dom/signals.js, Andrea Giammarchi.
- browser-compat-data, MDN.
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.