Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Svelte 5: $effect in child component unexpectedly being triggered by parent component $state change #10603

Closed
tommyminds opened this issue Feb 22, 2024 · 1 comment · Fixed by #10605

Comments

@tommyminds
Copy link

tommyminds commented Feb 22, 2024

Describe the bug

I've run in a strange issue where an $effect seems triggered by a parent component's state change when it shouldn't be causing it to go into an infinite loop and throwing an ERR_SVELTE_TOO_MANY_UPDATES: Maximum update depth exceeded. This can happen when a reactive block or effect repeatedly sets a new value. Svelte limits the number of nested updates to prevent infinite loops.

Reproduction

Link to REPL

Parent component:

<script>
    import { setContext } from 'svelte';
    import Item from './Item.svelte'

    let items = $state({});

    setContext('container', {
        register: (id) => items[id] = true,
        unregister: (id) => delete items[id]
    });
</script>

<Item />

Child component:

<script>
    import { getContext } from 'svelte';

    let context = getContext('container');
    
    $effect(() => {
        context.register('test');
        return () => context.unregister('test');
    });
</script>

<div>Item</div>

Logs

No response

System Info

System:
    OS: macOS 14.3.1
    CPU: (8) arm64 Apple M1 Pro
    Memory: 90.39 MB / 32.00 GB
    Shell: 5.9 - /bin/zsh
Binaries:
    Node: 18.9.0 - ~/.nvm/versions/node/v18.9.0/bin/node
    Yarn: 1.22.19 - ~/.nvm/versions/node/v18.9.0/bin/yarn
    npm: 9.9.2 - ~/.nvm/versions/node/v18.9.0/bin/npm
    pnpm: 8.15.1 - /opt/homebrew/bin/pnpm
    bun: 1.0.26 - /opt/homebrew/bin/bun
Browsers:
    Chrome: 121.0.6167.184
    Safari: 17.3.1
npmPackages:
    svelte: ^5.0.0-next.65 => 5.0.0-next.65

Severity

annoyance

@dummdidumm
Copy link
Member

This works as expected, although it's tricky at first to understand why. The reason is that items[id] is a read which is becoming a signal dependency to the effect. Because items[id] is undefined initially and after doing the assignment it's true, it's firing an update event immediately. That causes the effect to rerun, which means the cleanup function is called which sets it back to undefined, and so it happens over and over again.
For one-off stuff like this it's probably easier to use onMount instead.

@dummdidumm dummdidumm closed this as not planned Won't fix, can't repro, duplicate, stale Feb 22, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants