• Tracks reactive items used by the specified data function and subscribes the provided callback function to changes in these items. This ensures that the callback is executed whenever any of the tracked dependencies change, allowing for reactive updates based on the data function.

    Parameters

    • dataFunction: (() => any)

      The function whose reactive dependencies are tracked.

        • (): any
        • Returns any

    • fn: ((updates?) => void)

      The callback function to execute when tracked dependencies change.

        • (updates?): void
        • Parameters

          Returns void

    • Optional options: {
          delay: number;
          name: string;
          signal: AbortSignal;
          type: string;
      }

      The options for the reaction function.

      • delay: number

        The number of milliseconds to delay the execution of the callback function.

      • name: string

        An optional name for the reaction.

      • signal: AbortSignal

        An optional signal to abort the reaction.

      • type: string

        An optional type for the reaction. Defaults to "reaction".

    Returns (() => void)

    A function that can be called to unsubscribe the callback function from changes in the tracked dependencies.

      • (): void
      • Returns void

    Example

    const a = atom(0);
    const b = atom(0);

    let foo = 0;

    // runs only data-function to get dependencies
    // and then subscribes to changes in a and b
    reaction(
    () => [a.value, b.value],
    () => {
    foo++;
    }
    );

    console.log(a.value, b.value, foo); // 0 0 0

    a.value++;
    console.log(a.value, b.value, foo); // 1 0 1

    b.value++;
    console.log(a.value, b.value, foo); // 1 1 2

    batch(() => {
    a.value++;
    b.value++;
    });

    console.log(a.value, b.value, foo); // 2 2 3