• Watches reactive values and executes a callback whenever those values change.

    watch works like this:

    1. The selector is a tracked function that shall return an array of values. Those values are usually obtained by accessing one or more reactive objects.
    2. Whenever the values inside the array returned by selector change, callback will be executed with those values (the old values are available as well). The body of callback is not reactive.

    The arrays returned by the selector are compared using shallow equality by default: the callback runs if the length of the array changes or if one of its entries has a different identity. Note that you can provide a custom equal function to change this behavior.

    Example:

    const r1 = reactive(1);
    const r2 = reactive(2);
    watch(
    // Selector: reactive code (may be complex, but should be fast).
    () => [r1.value, r2.value, r1.value + r2.value],

    // Callback: only executes if selector returns different values.
    ([v1, v2, v3]) => {
    console.log(v1, v2, v3);
    }
    );

    watch returns a handle that can be used to unsubscribe from changes. That handle's destroy() function should be called to stop watching when you are no longer interested in updates:

    const handle = watch(() => [someReactive.value], () => {
    // ...
    });
    // later:
    handle.destroy();

    NOTE: You must not modify the parameters that get passed into callback.

    NOTE: This function will slightly defer re-executions of the given callback. In other words, the re-execution does not happen immediately after a reactive dependency changed. This is done to avoid redundant executions as a result of many fine-grained changes.

    If you need more control, take a look at syncWatch.

    Type Parameters

    • const Values extends unknown[]

    Parameters

    Returns CleanupHandle

  • This overload is used when immediate is not set to false.

    Type Parameters

    • const Values extends unknown[]

    Parameters

    Returns CleanupHandle