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.
It also accepts an array of sources.
The callback receives two arguments: The current value of the sources, and the previous value.
watch
also accepts an options
object.
watch.pre
watch.pre
is similar to watch
, but it uses $effect.pre
under the hood.