• Automatically tracks and subscribes to changes in reactive items used by the specified function. This allows the function to be re-executed whenever any of its dependencies change, maintaining up-to-date results.

    Parameters

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

      The function to track and reactively execute.

        • (updates?): void
        • Parameters

          Returns void

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

      The options for the autorun function.

      • delay: number

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

      • name: string

        An optional name for the autorun.

      • onError: Function

        An optional function to handle errors.

      • signal: AbortSignal

        An optional AbortSignal to cancel the autorun.

    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, { name: "a" });
    const b = atom(0, { name: "b" });
    let foo = 0;

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

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

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

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

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

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