Skip to content

$derived unexpectedly reevaluate #15414

@CNSeniorious000

Description

@CNSeniorious000

Describe the bug

The reactivity system don't work as expect.

Consider the code below:

  1. cycle is an iterator, calling cycle() will get 1, 2, 1, 1, then 1, 2, 1, 1, etc.
  2. a is a $state, and I invoke an setInterval to () => a = cycle(), so that a will be 1, 2, 1, 1 ... right?
  3. const b = $derived(a)
  4. const c = $derived(b)
  5. an $effect used c. Let's say $effect(() => { const _ = c }

So, the ideal results should be:

  1. when the effect first run, it used c, c used b, b used a, and a is 1;
  2. when a set to 2, b invalidates and set to 2, c invalidates and set to 2;
  3. when a set to 1, b invalidates and set to 1, c invalidates and set to 1;
  4. when a set to 1, b doesn't invalidate, c doesn't invalidate;
  5. when a set to 2, b invalidates and set to 2, c invalidates and set to 2;

...

Right? But now in the #4 step, b doesn't invalidate, but c invalidates.

In the reporduction below, I replaced the cycle with a button to let you control more.

And I log every $derived reruns by using

let b = $derived((console.log("b", { a }), a));

Reproduction

https://svelte.dev/playground/a727bfaac87f41bdbe3d007f9928e5dc?version=5.20.5

Open the console and click the button 3 times.

After you clicked the 4th time, you are on the #4 state described above.

Expected output:

a { value: 1 }
b { a: 1 }
c { b: 1 }
a { value: 2 }
b { a: 2 }
c { b: 2 }
a { value: 1 }
b { a: 1 }
c { b: 1 }
a { value: 1 }

Actual output:

a { value: 1 }
b { a: 1 }
c { b: 1 }
a { value: 2 }
b { a: 2 }
c { b: 2 }
a { value: 1 }
b { a: 1 }
c { b: 1 }
a { value: 1 }
c { b: 1 }     <- this line should never show!!

Logs

System Info

  System:
    OS: Windows 11 10.0.26100
    CPU: (16) x64 AMD Ryzen 7 7840HS w/ Radeon 780M Graphics
    Memory: 3.25 GB / 14.68 GB
  Binaries:
    Node: 22.14.0 - D:\Program Files\nodejs\node.EXE
    npm: 10.9.2 - D:\Program Files\nodejs\npm.CMD
    pnpm: 10.5.2 - ~\.bun\bin\pnpm.EXE
    bun: 1.2.4 - ~\.bun\bin\bun.EXE
  Browsers:
    Edge: Chromium (131.0.2903.86)
    Internet Explorer: 11.0.26100.1882
  npmPackages:
    svelte: ^5.20.5 => 5.20.5

Severity

annoyance

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions