Performance: svelte:self for recursive components
This affects rendering performance by controlling how recursive components render and update in the browser.
<script> export let node; </script> <div> {node.name} {#each node.children as child} <svelte:self node={child} /> {/each} </div>
<script> export let node; </script> <div> {node.name} {#each node.children as child} <Component node={child} /> {/each} </div>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Using component name recursively | Many nested components created | Multiple reflows per recursive level | High paint cost due to many updates | [X] Bad |
| Using svelte:self for recursion | Reuses component instance | Single reflow per update cycle | Lower paint cost with efficient updates | [OK] Good |
svelte:self in a Svelte component?svelte:selfsvelte:self is a special tag that lets a component include itself inside its own template.svelte:self with dynamic importssvelte:self?<svelte:self />.<svelte:self /> for recursion [OK]Component.self which is invalidsvelte: prefixself() as a function <script>
export let node;
</script>
<div>{node.name}</div>
{#if node.children}
<ul>
{#each node.children as child}
<li><svelte:self node={child} /></li>
{/each}
</ul>
{/if}node is:{"name": "Root", "children": [{"name": "Child1"}, {"name": "Child2"}]}{#each} with svelte:self [OK]{#if} condition for children<script>
export let node;
</script>
<div>{node.name}</div>
<svelte:self node={node.children[0]} />node.children can be empty or undefined.node.children[0] without checking if children exist or have elements.node.children is empty or undefined, the recursion never stops, causing infinite recursion or runtime errors.node.children is empty or undefined. -> Option Asvelte:self call [OK]svelte:self. Each comment has a text and optional replies array. Which approach correctly prevents infinite recursion and shows all comments?replies exists and has items.{#if replies && replies.length} and {#each replies as reply} with <svelte:self /> passing reply.replies exists and is not empty, recursively render svelte:self for each reply inside a list. -> Option BPass the test and this pattern moves unknown