• Creates a reactive effect that automatically tracks signal dependencies.

    Effects automatically re-run when any signals they read change. This is the foundation of reactive programming - side effects that stay in sync with state.

    Isomorphic: Works identically across all JavaScript runtimes. Performance: Only re-runs when dependencies actually change. Cleanup: Automatic dependency cleanup when effect re-runs.

    Parameters

    • fn: (() => void | Promise<void>)

      Function to run reactively

        • (): void | Promise<void>
        • Returns void | Promise<void>

    Returns (() => void | Promise<void>)

    Disposal function to stop the effect

      • (): void | Promise<void>
      • Returns void | Promise<void>

    // Basic reactive effect
    const count = signal(0);

    const dispose = effect(() => {
    console.log('Count is:', count());
    });

    count.set(1); // Logs: "Count is: 1"
    count.set(2); // Logs: "Count is: 2"

    dispose(); // Stop the effect
    count.set(3); // No log (effect disposed)
    // Async effects work seamlessly
    const data = signal(null);

    effect(async () => {
    if (data()) {
    await fetch('/api/track', {
    method: 'POST',
    body: JSON.stringify(data())
    });
    }
    });