Lifecycle and cleanup
This page covers when effects rerun, which owner releases their cleanups, and how context and errors move through a Reze app. After reading it, you can release resources when a component or scope ends and handle errors from effects and computed values.
Effects and scheduling
effect runs its function once, then reruns it after a signal or computed value it read changes. A write does not rerun the effect during the write. The rerun is queued on a microtask, so several writes in the same tick cause one rerun with the latest value.
The following module logs count is 0 when it loads. The two writes queue one rerun, which logs count is 2 on the next microtask:
import { effect, signal } from "reze-js";
let count = signal(0);
effect(() => {
console.log("count is", count);
});
count = 1;
count = 2;
Rerun after writes
A read of the signal in the same task returns the value you wrote. Only the effect waits for the microtask. Use flush when the rerun must happen before the next line runs. flush runs every queued effect now, including effects that the rerun queues.
The following module logs count is 0, then count is 1, then after flush:
import { effect, flush, signal } from "reze-js";
let count = signal(0);
effect(() => {
console.log("count is", count);
});
count = 1;
flush();
console.log("after flush");
Cleanup before each rerun
Call onCleanup inside an effect to register a function that runs before the effect reruns and when its owner disposes it. The next run starts only after the cleanup finishes.
The following module logs effect 0, then cleanup 0, then effect 1 after the flush:
import { effect, flush, onCleanup, signal } from "reze-js";
let count = signal(0);
effect(() => {
const value = count;
console.log("effect", value);
onCleanup(() => console.log("cleanup", value));
});
count = 1;
flush();
Untracked reads
untrack runs a function without subscribing the surrounding effect to the signals it reads. Use it to read a value that should not cause a rerun.
The following module reruns only when count changes. Writing label through setLabel logs nothing:
import { effect, signal, untrack } from "reze-js";
let count = signal(0);
let label = signal("count");
export function setCount(next: number) {
count = next;
}
export function setLabel(next: string) {
label = next;
}
effect(() => {
const current = count;
console.log(
untrack(() => label),
current,
);
});
Ownership and cleanup
Every effect, computed value, and onCleanup callback belongs to an owner. An owner is created by a component, an effect, root, or effectScope. When an owner disposes, it disposes its children first, then runs its cleanups in reverse registration order.
Dispose a root
root creates an owner that is not attached to the current one. Its callback receives a dispose function. Return that function from the callback to dispose the root later. root returns the callback's return value.
The following module logs second registered, then first registered:
import { onCleanup, root } from "reze-js";
const stopRoot = root((dispose) => {
onCleanup(() => console.log("first registered"));
onCleanup(() => console.log("second registered"));
return dispose;
});
stopRoot();
Effect scopes
effectScope runs its function once in a new owner and returns a disposer. Reads in the function do not rerun the function, but effects created inside it do rerun. Calling the disposer stops those effects.
The following module logs scope sees 0, then scope sees 1. After stop(), the write to count logs nothing:
import { effect, effectScope, flush, signal } from "reze-js";
let count = signal(0);
const stop = effectScope(() => {
effect(() => {
console.log("scope sees", count);
});
});
count = 1;
flush();
stop();
count = 2;
flush();
Component cleanup
A component runs once, untracked, under the owner that mounts it. Its onCleanup callbacks run when that mount is disposed. Calling the disposer that render returns disposes the mounted tree, then empties the element.
The following component clears its timer when it unmounts:
import { onCleanup } from "reze-js";
export function Clock() {
const timer = setInterval(() => console.log("tick"), 1000);
onCleanup(() => clearInterval(timer));
return <p>Clock</p>;
}
Owners across async work
Code that runs after an await is not owned by the surrounding root, component, or effect. The same applies to timer callbacks. getOwner returns the current owner, or undefined outside any owner. Outside an owner, onCleanup does nothing.
To attach work to an owner after an await, capture the owner before the await and pass it to runWithOwner. A microtask that does this before the owner disposes registers its cleanup on that owner:
import { getOwner, onCleanup, root, runWithOwner } from "reze-js";
const stopRoot = root((dispose) => {
const owner = getOwner();
queueMicrotask(() => {
runWithOwner(owner, () => {
onCleanup(() => console.log("late cleanup"));
});
});
return dispose;
});
Disposing stopRoot after the microtask runs logs late cleanup. If the root is already disposed, runWithOwner does not run the cleanup.
For async component bodies, which load their data after the first await, see async components.
Context
createContext makes a value that descendants read with useContext. A context created with a default returns that default when no provider is above the reader. A provider is the context used as a JSX element with a value prop.
The following module renders dark, because ThemeLabel reads the nearest provider:
import { createContext, useContext } from "reze-js";
const Theme = createContext("light");
function ThemeLabel() {
return <span>{useContext(Theme)}</span>;
}
export function App() {
return (
<Theme value="dark">
<ThemeLabel />
</Theme>
);
}
Missing providers
A context created without a default throws ContextNotFoundError when useContext runs with no provider above it. Create the context with a default when a missing provider is valid.
import { createContext, useContext } from "reze-js";
const Session = createContext<string>();
export function SessionLabel() {
return <span>{useContext(Session)}</span>;
}
Provider values
A provider passes its value once for the children it renders. Passing a signal directly as value does not update children when the signal changes. To let children read the latest value, pass a getter and call it where the value is used.
The following module updates the rendered label when setTheme runs, because the child calls the getter inside its JSX:
import { createContext, signal, useContext } from "reze-js";
const Theme = createContext<() => string>(() => "light");
function ThemeLabel() {
return <span>{useContext(Theme)()}</span>;
}
let theme = signal("dark");
const readTheme = () => theme;
export function setTheme(value: string) {
theme = value;
}
export function App() {
return (
<Theme value={readTheme}>
<ThemeLabel />
</Theme>
);
}
Provide without JSX
provideContext runs a function with a value provided for a context and returns the function's result. Use it when the code that needs the provider is not written as JSX. The provided value is visible to useContext calls inside the function, and to anything created inside it.
import { createContext, provideContext, useContext } from "reze-js";
const Theme = createContext("light");
export function themeFor(value: string) {
return provideContext(Theme, value, () => useContext(Theme));
}
Errors
catchError runs a function under an owner that handles errors. It returns the function's result, or undefined if the function throws. A throw from an effect, computed value, or binding created inside the function goes to the handler.
Error handlers
The following module logs handled count reached 1 after flush reruns the effect with the new value:
import { catchError, effect, flush, signal } from "reze-js";
let count = signal(0);
catchError(
() => {
effect(() => {
if (count === 1) {
throw new Error("count reached 1");
}
});
},
(error) => console.log("handled", (error as Error).message),
);
count = 1;
flush();
Computed errors
When a computed value throws after its first run, the handler receives the error, and the computed value keeps its previous value. A computed value that throws on its first run throws to the caller unless a catchError handler is above it.
The following module logs inverse 1, then handled input is zero. The computed value stays at 1:
import { catchError, computed, effect, flush, signal } from "reze-js";
let input = signal(1);
function reciprocal(value: number): number {
if (value === 0) {
throw new RangeError("input is zero");
}
return 1 / value;
}
catchError(
() => {
const inverse = computed(reciprocal(input));
effect(() => {
console.log("inverse", inverse);
});
},
(error) => console.log("handled", (error as Error).message),
);
input = 0;
flush();
Nested handlers
A throw from a handler during a synchronous catchError call goes to the enclosing catchError handler. A throw from a handler during a scheduled rerun does not. It escapes the flush call that ran the rerun, and the enclosing handler does not run.
Related pages
- Reactivity covers
signal,computed,store, andaction. - Components covers component execution, props, and children.
- Building interfaces covers async components, portals, and other rendering patterns.
- Vite plugin covers build and static site generation settings.