Consider a Svelte component that uses <svelte:self> to render a nested list recursively. What will be the rendered output for the given data?
<script> export let node; </script> <ul> <li>{node.name}</li> {#if node.children} <ul> {#each node.children as child} <svelte:self node={child} /> {/each} </ul> {/if} </ul>
Think about how <svelte:self> calls the same component recursively for each child node.
The component renders an unordered list. For each node, it shows the node's name in a list item. If the node has children, it recursively renders each child inside a nested <ul>. This creates nested lists reflecting the tree structure.
<svelte:self> for recursion?Which of the following Svelte snippets correctly uses <svelte:self> to recursively render a tree structure?
Remember that <svelte:self> calls the same component and you must pass a single node, not an array, for recursion.
Option A correctly passes a single child node to <svelte:self> for recursive rendering. Option A passes an array to a prop named differently, which is incorrect. Option A passes the whole item again, causing infinite recursion. Option A passes an array instead of a single node, which is incorrect.
Given this Svelte component using <svelte:self>, why does it crash with a maximum call stack exceeded error?
<script> export let node; </script> <ul> <li>{node.name}</li> {#if node.children} {#each node.children as child} <svelte:self node={node} /> {/each} {/if} </ul>
Check what is passed to <svelte:self> inside the loop.
The component passes the same node prop to <svelte:self> inside the loop, so it calls itself infinitely with the same data, causing a stack overflow.
count after clicking all buttons in this recursive Svelte component?This component renders buttons recursively using <svelte:self>. Each button increments a shared count state. What is the final count after clicking all buttons once?
<script> import { writable } from 'svelte/store'; export let node; const count = writable(0); function increment() { count.update(n => n + 1); } </script> <div> <button on:click={increment}>{node.name}</button> {#if node.children} {#each node.children as child} <svelte:self node={child} /> {/each} {/if} <p>Count: {$count}</p> </div>
Consider that count is a shared store imported once and used by all instances.
The count store is shared across all recursive instances. Clicking each button increments the same store, so after clicking all buttons once, the count equals the total number of nodes rendered.
<svelte:self> instead of importing the component for recursion?In Svelte, what is the main advantage of using <svelte:self> for recursive components instead of importing the component by name and calling it recursively?
Think about how importing a component inside itself can cause problems.
<svelte:self> lets a component call itself recursively without needing to import itself, which avoids circular import errors and keeps recursion simple and clean inside one file.