Closed
Description
Describe the bug
<script>
let count = $state(0);
function increment() {
count += 1;
}
$effect(() => {
const doubled = count * 2;
$effect(() => {
//This nested effect is destroyed and recreated everytime count changes. So we log count to the console ONCE every update
console.log({count, doubled});
})
})
</script>
<button onclick={increment}>
Increment
</button>
In code above the nested effect and it's parent both track the same piece of state and as expected the code in the nested effect executes once everytime count is updated.
But if we replace the parent effect with a template effect:
<script>
let count = $state(0);
function increment() {
count += 1;
}
</script>
<button onclick={increment}>
clicks: {count}
</button>
<p>{(() => {
const doubled = count * 2;
$effect(() => {
//Logs twice on every update to count, in the second log doubled is always 0
console.log({count, doubled})
})
return count
})()}</p>
I found that the code in the nested effect executes twice for every update to count. In the first run doubled is always up to date but the second run references a stale closure so doubled is always 0. I'm guessing that the effect that references the stale closure somehow escapes destruction, so this is a memory leak? Or is it a feature of template effects that I'm not aware of
Reproduction
Logs
No response
System Info
System:
OS: Linux 6.8 Linux Mint 22 (Wilma)
CPU: (4) x64 Intel(R) Core(TM) i5-6300U CPU @ 2.40GHz
Memory: 1.86 GB / 7.64 GB
Container: Yes
Shell: 5.2.21 - /bin/bash
Binaries:
Node: 20.17.0 - ~/.nvm/versions/node/v20.17.0/bin/node
npm: 10.8.2 - ~/.nvm/versions/node/v20.17.0/bin/npm
pnpm: 9.10.0 - ~/.nvm/versions/node/v20.17.0/bin/pnpm
Severity
annoyance