-
-
Notifications
You must be signed in to change notification settings - Fork 58
Description
Motivation
We encountered a strange situation where the components from two different branches of #if / :else if statement were rendered at the same time.
Svelte swaps if/else if branches using its normal diffing and transition logic, which can briefly put both branches in the DOM at the same time (especially if either branch has intros/outros or any pending microtasks):
-
Svelte tries to be smart and reuse/update DOM between mutually exclusive blocks.
-
When the condition flips, Svelte runs the outgoing block’s outro and the incoming block’s intro concurrently by default; during that period both components exist in the DOM, so you can see a flash of both.
Description
With #key, Svelte destroys the old branch first, then creates the new one, so there is no momentary overlap.
Examples
<!-- ✓ GOOD -->
{#key currentStep}
{#if currentStep === "step1"}
<Cmp1 />
{:else if currentStep === "step2"}
<Cmp2 />
{/if}
{/key}
<!-- ✗ BAD -->
{#if currentStep === "step1"}
<Cmp1 />
{:else if currentStep === "step2"}
<Cmp2 />
{/if}Additional comments
Another solution could be to await tick() when changing conditions, but it seems more of a workaround than a solution.