Performance: svelte:component for dynamic components
This affects rendering speed and responsiveness by dynamically switching components at runtime.
<script> import ComponentA from './ComponentA.svelte'; import ComponentB from './ComponentB.svelte'; let showA = true; </script> {#if showA} <ComponentA /> {:else} <ComponentB /> {/if}
<svelte:component this={component} /> <script> let component = ComponentA; // component changes frequently on user input </script>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Dynamic svelte:component with frequent changes | High (destroy + create nodes) | Multiple reflows per change | High paint cost due to full component redraw | [X] Bad |
| Conditional rendering with {#if} blocks | Low (only toggles visibility) | Single reflow per toggle | Lower paint cost, partial updates | [OK] Good |
svelte:component tag do in Svelte?svelte:componentsvelte:component.svelte:component = dynamic rendering [OK]svelte:component means dynamic component rendering [OK]CurrentComp?svelte:component and the attribute to specify the component is this.<svelte:component this={CurrentComp} /> uses correct tag and attribute syntax. Others use wrong tags or attributes.this attribute = <svelte:component this={CurrentComp} /> [OK]svelte:component this={variable} for dynamic components [OK]component instead of svelte:componentsrc instead of this <script>
import A from './A.svelte';
import B from './B.svelte';
let comp = A;
</script>
<svelte:component this={comp} />
<button on:click={() => comp = B}>Switch</button>comp starts as component A, so A renders initially.comp to B, which triggers Svelte to render component B dynamically.this changes component = The displayed component switches from A to B. [OK]this variable updates the rendered component [OK]<script>
import X from './X.svelte';
let comp = 'X';
</script>
<svelte:component this={comp} />compcomp is assigned the string 'X', but it should hold the imported component itself.this attribute requirementsthis expects a component reference, not a string name.this needs component, not string [OK]this [OK]svelte:component can't be self-closingthisCat and Dog both accept a name prop, how do you pass name="Buddy" to the dynamic component stored in petComp?svelte:component.<svelte:component this={petComp} name="Buddy" /> correctly passes name="Buddy". <svelte:component this={petComp} {name}="Buddy" /> uses invalid syntax. <svelte:component this={petComp} props={{name: 'Buddy'}} /> tries to pass props as an object, which is not supported. <svelte:component this={petComp} bind:name="Buddy" /> uses bind: incorrectly.svelte:component [OK]svelte:component [OK]Pass the test and this pattern moves unknown