Guide

Reactivity

signal, memo and effect are the whole model. How they subscribe on their own, when they run and how they are released.

Three primitives

What it is Has a value Recomputes
signal State. The only thing you write. Yes Never
memo A value derived from others. Yes Lazily, when read
effect Work with side effects: touching the DOM, a fetch, a log. No After the write that affects it
ts
import { effect, memo, signal } from "ascua";

const price = signal(1000);
const quantity = signal(3);
const total = memo(() => price() * quantity());

effect(() => console.log(`Total: ${total()}`));   // Total: 3000
quantity.set(4);                                   // Total: 4000

Nobody declared that total depends on price and quantity, or that the effect depends on total. It is found by reading: while a memo or an effect runs, the runtime records what it read. If next time it reads other things —a branch of an if that changed—, it subscribes to those and stops listening to the previous ones.

signal

ts
const name = signal("Ana");

name();                        // read, and subscribe if someone is listening
name.set("Luis");              // write
name.update((n) => n.trim());  // write based on the current value
name.peek();                   // read without subscribing

Writing the value it already had (Object.is) wakes nobody.

A signal holds a reference: mutating an array or an object in place does not notify. You write a new one:

ts
const tasks = signal<Task[]>([]);

tasks.update((list) => [...list, task]);   // ✓ notifies
tasks().push(task);                           // ✗ nobody finds out

memo

ts
const visible = memo(() => tasks().filter((t) => !t.done));

A memo is lazy: it does not compute until someone reads it, and it does not compute again while its sources do not change. And it stops propagation: if it gets the same value when recomputing, whoever reads it does not find out.

ts
const isBig = memo(() => count() > 100);
// count: 1 → 2 → 3 … → 100: isBig is still false and nothing repaints.

The second argument changes what counts as "the same value":

ts
const punto = memo(() => ({ x: x(), y: y() }), (a, b) => a.x === b.x && a.y === b.y);

effect

ts
effect(() => {
  document.title = `${pending()} pending`;
});

It runs once when created and once more for each change that affects it. In a template you almost never write one by hand: each ${() => …} is an effect the compiler puts in for you.

Cleanup

ts
effect(() => {
  const id = setInterval(tick, intervalo());
  onCleanup(() => clearInterval(id));
});

onCleanup runs before each rerun and one last time when the effect is released. It is how you let go of what you acquired: an interval, a global listener, a subscription.

No intermediate states

Writing to a signal runs nothing: it marks. First everything that depends on it is marked, and only when the marking has finished propagating do the effects run. Two guarantees come from that:

  • An effect never sees a half-updated state. If b and c derive from a and an effect reads both, when a changes the effect runs once and sees both new values, never one new and one old.
  • An effect runs once per change, even if notices reach it by several paths.

batch

Several writes in a row are several changes. batch joins them into one:

ts
batch(() => {
  price.set(1200);
  quantity.set(2);
});
// Total: 2400 — just once, not twice.

untrack

Reading without subscribing, when an effect needs a piece of data but must not react to it:

ts
effect(() => {
  track(page(), untrack(() => user()));   // only reacts to page
});

Who owns what

Everything reactive has an owner: the scope that was active when it was created. Releasing an owner releases everything that hangs from it, in order.

ts
const [app, unmount] = root(() => {
  const count = signal(0);
  effect(() => console.log(count()));
  return count;
});

unmount();   // the effect stops existing and its onCleanup callbacks run

You almost never need to call root: mount, <Show>, <For> and the router create their own. When a <Show> branch closes, everything created inside it —effects, memos, listeners— is released with it. Nothing stays alive listening to a component that is no longer there.

When an effect reruns, before running it releases what it created the previous time: an effect created inside another effect does not pile up.

Data that arrives late: resource

ts
const club = resource(
  () => id(),                                   // the source: when it changes, it reloads
  (id, { signal }) => fetch(`/api/clubes/${id}`, { signal }).then((r) => r.json()),
);

view`
  <section>
    <Show when=${() => club.state() === "error"}><p>Could not load.</p></Show>
    <Show when=${() => club()}>${(c) => view`<h2>${() => c().name}</h2>`}</Show>
    <button onclick=${() => club.reload()}>Reload</button>
  </section>`;

club() is the last loaded value, club.state() says what it is doing (idle, loading, ready, error), club.error() holds the error and club.reload() loads again. If the source gives null, undefined or false, it does not load. Without a source, resource(({ signal }) => …) loads once.

What you do not have to write by hand:

  • A new load aborts the previous one, and its response is discarded even if it arrives: a slow result does not overwrite a more recent one.
  • Closing the view cancels what was in flight. The signal the function receives fires when the scope is released.
  • Reloading does not flicker. While the new value arrives, club() keeps giving the previous one; for an indicator, club.loading().
  • club.mutate(value) changes the value without loading: what you already know after saving.

Asynchronous code

After an await, the scope is no longer the one it was: the code runs in another turn of the event loop. If you need to create something reactive there, capture the scope first and restore it:

ts
const scope = currentScope();
const data = await fetch(url).then((r) => r.json());
withScope(scope, () => {
  effect(() => …);   // belongs to the component, and is released with it
});

Timers: timeout and interval

setTimeout and setInterval tied to the scope: if the component unmounts first, they cancel themselves. A notice that hides after three seconds does not write to the signal of a component that is gone:

ts
import { interval, timeout } from "ascua";

timeout(3000, () => notice.set(null));
interval(1000, () => seconds.update((s) => s + 1));

The callback runs like an effect, in the scope where it was created: an error goes to its onError, and what it writes goes out in a single batch. Both return a Timer with cancel(); on one that already ran it does nothing.

Inside an event handler there is no scope, so what you create there is not cancelled when the component unmounts. That is the debounce case: keep the last one and cancel it with onCleanup, which does run in the component body.

ts
let pending: Timer | undefined;
onCleanup(() => pending?.cancel());

const onInput = (text: string) => {
  pending?.cancel();
  pending = timeout(300, () => search(text));
};

The browser slows down timers in a background tab: to measure real time, use Date.now() at the start and at the end, and the interval only to refresh what is shown.

selector: picking one out of a thousand

The case is the selected row of a table. If each row reads the selection signal, changing it wakes a thousand effects to repaint two. With selector, each row subscribes only to its key:

ts
const selected = signal<number | null>(null);
const isSelected = selector(() => selected());

view`<tr class:selected=${() => isSelected(row.id)}>…</tr>`;

Changing selected notifies the row that stops being selected and the one that becomes selected. The other 998 never find out.

Saved in the browser: persisted

A signal that is saved to localStorage and comes back on the next visit:

ts
import { persisted } from "ascua/persisted";

const theme = persisted<"light" | "dark">("app:theme", "light");
theme.set("dark");   // in memory and, if it can, in localStorage
theme.saved();       // false if it could not be saved

The browser's storage fails more than it seems: it throws on read with cookies blocked or inside a sandboxed iframe, throws on write when the quota is full, and returns what an older version of the app left behind. persisted lets none of that break the page:

  • It reads once, when created. If there is nothing, the JSON is broken or the storage throws, the initial value is used.
  • Every set writes. If that fails, the signal keeps working in memory and saved() turns false, in case the interface wants to say so.
  • version. What is saved carries its version ({"v":1,"d":…}). When the shape of the data changes, raise the version and the old data is discarded instead of breaking the app. validate checks what was read.
  • sync: true follows changes to the same key from other tabs; the listener goes away with the scope.
  • Without storage —on the server, in a test— it works in memory only. storage swaps the store: sessionStorage, or a fake one in tests.

It lives in its own subpath so it weighs nothing for those who don't use it: about 0.3 kB.

Errors

An error inside an effect goes up through the owners to the first one that has an onError. It is covered in Errors and debugging.