watch
Watch for changes and run a callback
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 a getter function, which returns the dependencies of the
effect callback.
Usage
watch
Runs a callback whenever one of the sources change.
The callback receives two arguments: The current value of the sources, and the previous value.
You can also send in an array of sources:
watch
also accepts an options
object.
watch.pre
watch.pre
is similar to watch
, but it uses $effect.pre
under the hood.
watchOnce
In case you want to run the callback only once, you can use watchOnce
and watchOnce.pre
. It
functions identically to the watch
and watch.pre
otherwise, but it does not accept any options
object.