Why doesn't this assignment cause an infinite loop in $effect()? #16931
-
| I have this Svelte 5 component: <script lang="ts">
    type Props = {
        player: Player;
        messages: string[];
    };
    let { player = $bindable(), messages = $bindable() }: Props = $props();
    $effect(() => {
        const selected: string[] = [];
        if (player.skills?.some((s) => s.one)) selected.push('One');
        if (player.skills?.some((s) => s.two)) selected.push('Two');
        if (player.skills?.some((s) => s.three)) selected.push('Three');
        messages.push(`Please verify: ${selected.join(', ')}`);
    });
</script>
{#each player.skills || [] as skill, i (skill.id)}
    <Skill bind:skill={player.skills[i]} />
{/each}but when I check a skill.one/two and so on (boolean values) in one of the  If I use the below code instead it works. $effect(() => {
    // The same as before
    
    messages = selected.length ? [`Please verify: ${selected.join(', ')}`] : [];
});Why doesn't assignment cause an infinite loop? | 
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
| 
 The assignment on the other hand does not perform any reads, thus not creating a dependency on  (You can use  | 
Beta Was this translation helpful? Give feedback.
messages.pushis a read operation onmessagesandpushalso reads thelengthwhile at the same time modifying thelength. The combination of reading and writing causes the loop.The assignment on the other hand does not perform any reads, thus not creating a dependency on
messages.(You can use
$inspect.trace()inside an effect to check the dependencies. This will showmessages.lengthin your looping code.)