useMemo
Creates a cached derivation that recomputes only when a dependency actually changed.
Creates a cached derivation that recomputes only when a dependency actually changed.
Dependencies are discovered on every run, so branches that are not taken are not tracked.
A memo that throws inside an error boundary (an ancestor onError or catchError) reports the
error there and keeps its previous value; without a boundary it stores the error and rethrows it
to every reader.
Import#
ts
import { useMemo } from "@shadow-js/core";
Signature#
ts
function useMemo<T>(
fn: (previous: T | undefined) => T,
options?: MemoOptions<T>,
): Accessor<T>
Parameters#
| Name | Description |
|---|---|
fn |
Computation; receives the previous value (undefined on the first run). |
options |
Equality override, lazy, allowWrites and a devtools name. Undefined uses the defaults. |
Returns#
An accessor returning the current, always fresh value.
Throws#
- ShadowError
CYCLE_DETECTEDfrom the accessor when the memo reads itself while it computes. Outside an error boundary the accessor also rethrows the errorfnthrew on its last run.
Examples#
ts
import { useMemo, useSignal } from "@shadow-js/core";
const [count, setCount] = useSignal(2);
const doubled = useMemo(() => count() * 2);
setCount(5);
console.log(doubled()); // 10