@gluonjs/reactivity


@gluonjs/reactivity / packages/reactivity/src / watchEffect

Function: watchEffect()

watchEffect(callback, options?): WatchStopHandle

Parameters

callback

WatchEffectCallback

options?

WatchOptions = {}

Returns

WatchStopHandle

Example

Run an effect-style watcher immediately, infer dependencies from its reads, and clean up before the next run:

ts
import {
  ref,
  watch,
  watchEffect,
  type WatchCallback,
  type WatchCleanup,
  type WatchCleanupRegistrar,
  type WatchEffectCallback,
  type WatchOptions,
  type WatchSource,
  type WatchStopHandle,
} from '@gluonjs/reactivity';

const count = ref(0);
const source: WatchSource<number> = count;
const cleanup: WatchCleanup = () => console.log('previous request cancelled');
const registerCleanup: WatchCleanupRegistrar = (callback) => { void callback; };
registerCleanup(cleanup);
const callback: WatchCallback<number> = (value, previous, onCleanup) => {
  console.log(previous, '->', value);
  onCleanup(cleanup);
};
const options: WatchOptions = { immediate: true, flush: 'post' };
const stopWatch: WatchStopHandle = watch(source, callback, options);
const effectCallback: WatchEffectCallback = (onCleanup) => {
  console.log(count.value);
  onCleanup(cleanup);
};
const stopEffect: WatchStopHandle = watchEffect(effectCallback);
count.value = 1;
stopEffect();
stopWatch();