Performance: Use directive syntax
This affects how efficiently Svelte updates the DOM and handles reactive behavior during user interactions.
<input bind:value={name} /><input value={name} on:input={(e) => name = e.target.value} />| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual event handling for input | Multiple event listeners | Multiple reflows per keystroke | High paint cost due to frequent updates | [X] Bad |
| Svelte bind directive for input | Minimal DOM updates | Single reflow per change | Low paint cost | [OK] Good |
| CSS visibility toggle for conditional content | DOM nodes remain | Reflows on layout changes | Higher paint cost | [X] Bad |
| Svelte if directive for conditional content | DOM nodes added/removed | Reflows only when toggled | Lower paint cost | [OK] Good |
{#if}, {#each}, on:, or bind:?{#if}{#if} directive in Svelte shows or hides content based on a condition.{#each} loops over lists, on: handles events, and bind: links variables to inputs.{#if} -> Option B{#if} [OK]on:eventName={handler} to listen to events like clicks.<button on:click={handleClick}>Click</button> uses on:click correctly. Options A, B, and D use incorrect or invalid syntax.<script>
let items = ['apple', 'banana'];
</script>
<ul>
{#each items as item}
<li>{item}</li>
{/each}
</ul>items and assigns each element to item.item, it creates a <li> element with the item text inside.<script>
let count = 0;
</script>
<button on:click="count++">Increment</button>
<p>Count: {count}</p>on:click={count++}.done property?bind:checked links the checkbox's checked state directly to a variable, updating it automatically.<script>
let tasks = [
{ id: 1, text: 'Task 1', done: false },
{ id: 2, text: 'Task 2', done: true }
];
</script>
<ul>
{#each tasks as task}
<li>
<input type="checkbox" bind:checked={task.done} /> {task.text}
</li>
{/each}
</ul> uses bind:checked={task.done}, which is correct. <ul>
{#each tasks as task}
<li>
<input type="checkbox" checked={task.done} on:change={() => task.done = !task.done} /> {task.text}
</li>
{/each}
</ul> manually toggles on change but is more complex. <ul>
{#each tasks as task}
<li>
<input type="checkbox" bind:value={task.done} /> {task.text}
</li>
{/each}
</ul> uses bind:value which is incorrect for checkboxes. <ul>
{#each tasks as task}
<li>
<input type="checkbox" on:click={task.done = !task.done} /> {task.text}
</li>
{/each}
</ul> uses on:click without binding, which is less reactive.Pass the test and this pattern moves unknown