Learn / Zidom JS

Effects & lifecycle

Effects, batching, scopes and cleanup.

Effects react to dependencies#

effect(fn) executes immediately, tracks signals read during the call, then schedules future executions when those signals change. Normal writes schedule updates in a microtask.

ts
●  Zidom
import { signal, effect, flushSync } from '@zidomjs/core';const count = signal(0);const stop = effect(() => {  console.log('count =', count.value);});count.value = 1;flushSync(); // mainly for testing and integrationsstop();

Dynamic dependency tracking#

An effect tracks the values it actually reads on its latest execution, which matters for conditional state.

ts
●  Zidom
const showPrimary = signal(true);const primary = signal('A');const fallback = signal('B');const stop = effect(() => {  console.log(showPrimary.value ? primary.value : fallback.value);});// When showPrimary becomes false, the effect tracks fallback,// not primary, after its next execution.
ts
●  Zidom
import { batch, untrack } from '@zidomjs/core';batch(() => {  first.value = 'new first';  second.value = 'new second';});const snapshot = untrack(() => first.value);

Batching deduplicates effect work. untrack() reads a signal without adding that read as a dependency. Do not use it to hide data that should remain reactive.

Clean up with scopes#

ts
●  Zidom
import { createScope, onCleanup, signal, effect } from '@zidomjs/core';const tick = signal(0);const { scope } = createScope(() => {  const timer = setInterval(() => tick.value++, 1000);  onCleanup(() => clearInterval(timer));  effect(() => console.log(tick.value));});scope.dispose(); // timer + owned effects cleaned up

An effect can return a cleanup function, invoked before the next effect run and during disposal. An effect outside a scope must be stopped manually.

Next: Components & JSX and How Zidom works.

Run the example#

See the Zidom effects example and inspect the exact source next to the result.