effect
Runs fn as a render effect: synchronously when created, and again when the signals it reads change.
Runs fn as a render effect: synchronously when created, and again when the signals it reads
change. It is the effect the compiler emits for DOM bindings; application code usually prefers
useEffect. A function returned by fn is its cleanup, run before the next run and when the
owner disposes. It never runs on the server, and in development an effect created outside an
owner warns NO_OWNER_EFFECT.
Two-form render effect: compute is tracked and apply runs untracked with the new and the
previous value. A function returned by apply is its cleanup. Use it to keep the tracked reads
apart from the code that writes the DOM.
Import#
ts
import { effect } from "@shadow-js/web";
Signature#
ts
function effect(fn: () => void | Cleanup): void
function effect<T>(
compute: () => T,
apply: (value: T, previous: T | undefined) => void | Cleanup,
): void
Parameters#
| Name | Description |
|---|---|
fn |
Tracked body. Returns an optional cleanup function. |
compute |
Tracked. Its result is passed to apply. |
apply |
Untracked. Receives the value and the previous value (undefined on the first run) and returns an optional cleanup function. |
Examples#
ts
import { createRoot, useSignal } from "@shadow-js/core";
import { effect } from "@shadow-js/web";
const label = document.createElement("span");
createRoot(() => {
const [name] = useSignal("Ada");
effect(() => {
label.textContent = name(); // runs now, and again when name changes
});
});
ts
import { createRoot, useSignal } from "@shadow-js/core";
import { effect } from "@shadow-js/web";
const title = document.createElement("h1");
createRoot(() => {
const [text] = useSignal("Hello");
effect(text, (value, previous) => {
title.textContent = value;
console.log(previous); // undefined on the first run
});
});