watch

Category Lifecycle

Triggers a callback when a dependency changes.

Provides the previous value(s) as well as the current one(s) as parameters in the callback.

Usage

You can watch changes on a single value :

<script>
	import { watch } from '@sv-use/core';
 
	let counter = $state(0);
 
	watch(() => counter, (curr, prev) => {
        console.log(`Went from ${prev} to ${curr}`);
    });
</script>

Or on multiple values by supplying an array :

<script>
	import { watch } from '@sv-use/core';
 
	let counter = $state(0);
    let search = $state("");
 
	watch(
        [() => counter, () => search],
        ([currCounter, currSearch], [prevCounter, prevSearch]) => {
            // ...
        }
    );
</script>

onMount

By default, the callback runs when the component is first mounted in the DOM, as well as when a dependency changes.

You might not want that and only run when a dependency changes. You can set this in the options.

<script>
	import { watch } from '@sv-use/core';
 
	let counter = $state(0);
 
	watch(() => counter, (curr, prev) => {
        console.log(`Went from ${prev} to ${curr}`);
    }, { runOnMounted: false });
</script>
Type definitions
/**
 * Copied and adapted from Svecosystem Runed, all credit goes to them.
 * https://github.com/svecosystem/runed/blob/main/packages/runed/src/lib/utilities/watch/watch.svelte.ts
 */
import type { Getter } from '../../__internal__/types.js';
type WatchOptions<RunOnMounted extends boolean> = {
    /** Whether to run the effect on mount or not. */
    runOnMounted?: RunOnMounted;
};
export declare function watch<T, RunOnMounted extends boolean = true>(deps: Getter<T>, fn: (values: T, previousValues: RunOnMounted extends true ? T | undefined : T) => void, options?: WatchOptions<RunOnMounted>): void;
export declare function watch<T extends unknown[], RunOnMounted extends boolean = true>(deps: {
    [K in keyof T]: () => T[K];
}, fn: (values: T, previousValues: RunOnMounted extends true ? Array<T> | undefined : Array<T>) => void, options?: WatchOptions<RunOnMounted>): void;
export {};

Sources