Skip to content

Nested effect runs twice on state update when wrapped in template effect #13251

Closed
@levibassey

Description

@levibassey

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

https://svelte-5-preview.vercel.app/#H4sIAAAAAAAAA22RTY-cMAyG_4oVrbTQomHb43xJq96qqj30WHrIBEPTzTgocdgdofz3Csgwg7bJgeD4tZ33GUSjDXqx_TUIkmcUW_HcdaIQfOnGH9-jYRSF8DY4NUb2Xjnd8bEiAACDDMoGYjjAg2fJmD3lu4rm2yaQYm0JNCmHZyTOchjmu3HNyo8H-LSbg7Gifbk0qGh_CsyWwJIyWr0chqVQTANMcb-FYao16WfNrO-OQ5blcDhe2ypLnqG24WSwhkMa4QN8ThM8YNOg4rVoXGX5zbYe-FUrBEuAPboLhK6WjMB2LlSAJuA_CB6VpRqMbZde2oM0r_Li4eneAfLW4MbYNhtSiSSIefIkv6U75OBo7lVRzLM87svuKApxtrVuNNZiyy5gLBacHTqvPW8WkonsX39PFd866_gGLKkyTZoTshF1L03AG-rpdqTNY0Ia7upZe81fM9cNZMnkDTupXjS1Wb5K-Q-Fim_73rNKOHSBKpHGWHZZfrHB1PTIEDyCsUoaz9bJFgs4oZJj1EuqT_ZNU7sWf_354_vGs9PU6uaSTa9YN4j57jZvfAdoUqRoLNLBL4b098-9etpf88dvrCi-p_o7_gPvdLCasAMAAA==

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

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions