Why doesn't this assignment cause an infinite loop in $effect()? #16931
Answered
by
brunnerh
frederikhors
asked this question in
Q&A
|
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? |
Answered by
brunnerh
Oct 11, 2025
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 |
2 replies
Answer selected by
frederikhors
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.)