• Watches a single reactive value and executes a callback whenever that value changes.

    watchValue works like this:

    1. The selector is a tracked function that shall return a value. This value is usually obtained by accessing one or more reactive objects.
    2. Whenever the value returned by selector changes, callback will be executed with the new value (the old value is available as well). The body of callback is not reactive.

    The values returned by the selector are compared using object identity by default (i.e. Object.is). Note that you can provide a custom equal function to change this behavior.

    Example:

    import { reactive, watchValue } from "@conterra/reactivity-core";

    const v1 = reactive(1);
    const v2 = reactive(2);

    // Executes whenever the _sum_ of the two values changes.
    watchValue(() => v1.value + v2.value, (sum) => {
    console.log("new sum", sum);
    });

    watchValue 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 = watchValue(() => 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 syncWatchValue.

    Type Parameters

    • T

    Parameters

    • selector: ReactiveGetter<T>

      a function that returns the value to watch.

    • callback: WatchCallback<T>

      a function that will be executed whenever the watched value changes.

    • Optionaloptions: WatchOptions<T> & { immediate?: false }

      additional options.

    Returns CleanupHandle

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

    Type Parameters

    • T

    Parameters

    Returns CleanupHandle