0
0
Svelteframework~8 mins

svelte:component for dynamic components - Performance & Optimization

Choose your learning style9 modes available
Performance: svelte:component for dynamic components
MEDIUM IMPACT
This affects rendering speed and responsiveness by dynamically switching components at runtime.
Rendering different components dynamically based on user input
Svelte
<script>
  import ComponentA from './ComponentA.svelte';
  import ComponentB from './ComponentB.svelte';
  let showA = true;
</script>
{#if showA}
  <ComponentA />
{:else}
  <ComponentB />
{/if}
Using conditional rendering avoids unnecessary teardown and re-creation by letting Svelte optimize updates.
📈 Performance GainSingle reflow per toggle, smoother interaction, and less blocking of main thread.
Rendering different components dynamically based on user input
Svelte
<svelte:component this={component} />

<script>
  let component = ComponentA;
  // component changes frequently on user input
</script>
Frequent changes to 'this' cause full component teardown and re-creation, triggering multiple reflows and repaints.
📉 Performance CostTriggers multiple reflows and repaints on each component switch, blocking interaction for tens of milliseconds.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Dynamic svelte:component with frequent changesHigh (destroy + create nodes)Multiple reflows per changeHigh paint cost due to full component redraw[X] Bad
Conditional rendering with {#if} blocksLow (only toggles visibility)Single reflow per toggleLower paint cost, partial updates[OK] Good
Rendering Pipeline
When svelte:component changes, Svelte destroys the old component and creates a new one, causing layout recalculations and repaints.
Layout
Paint
Composite
⚠️ BottleneckLayout due to component teardown and re-creation
Core Web Vital Affected
INP
This affects rendering speed and responsiveness by dynamically switching components at runtime.
Optimization Tips
1Avoid changing the 'this' prop of svelte:component too often.
2Prefer conditional rendering with {#if} blocks for toggling components.
3Use svelte:component only when truly dynamic component selection is needed.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance cost of using <svelte:component> with frequent changes?
AFrequent component teardown and re-creation causing multiple reflows
BIncreased bundle size due to dynamic imports
CSlower initial page load due to server-side rendering
DHigher memory usage from caching components
DevTools: Performance
How to check: Record a performance profile while toggling the dynamic component. Look for frequent Layout and Recalculate Style events.
What to look for: Multiple Layout events and long scripting times indicate expensive component swaps.