Watch
Watch for changes and run a callback
Description
Runes provide a handy way of running a callback when reactive values change: $effect
. It automatically detects when
inner values change, and re-runs the callback.
$effect
is great, but sometimes you want to manually specify which values should trigger the
callback. Svelte provides an untrack
function, allowing you to specify that a dependency shouldn't be tracked, but it doesn't provide a way to say that only certain values should be
tracked.
watch
does exactly that. It accepts one or more sources, which can be getters
or boxes
.
Usage
watch
Runs a callback whenever one of the sources change.
import { watch, box } from "runed";
let count = $state(0);
watch(
() => count,
() => {
console.log(count);
}
);
let double = box.with(() => count * 2);
watch(double, () => {
console.log(double.value);
});
It also accepts an array of sources.
let age = $state(24);
let name = $state("Thomas");
watch([() => age, () => name], () => {
console.log(`${name} is ${age} years old`);
});
The callback receives two arguments: The current value of the sources, and the previous value.
let count = box(0);
watch(count, (curr, prev) => {
console.log(`count is ${curr}, was ${prev}`);
});
watch
also accepts an options
object.
watch(sources, callback, {
lazy: true, // First run will only happen after sources change
once: true // Will only run once
});
watch.pre
watch.pre
is similar to watch
, but it uses $effect.pre
under the hood.