Performance: Why actions add reusable element behavior
This affects how efficiently interactive behaviors are added to elements without extra DOM nodes or heavy JavaScript.
function clickAlert(node) { const handler = () => alert('Clicked!'); node.addEventListener('click', handler); return { destroy() { node.removeEventListener('click', handler); } }; } // Usage in component <div use:clickAlert>Click me</div> <div use:clickAlert>Click me too</div>
function addBehavior(node) { const handler = () => alert('Clicked!'); node.addEventListener('click', handler); return { destroy() { node.removeEventListener('click', handler); } }; } // Usage in component <div on:click={() => alert('Clicked!')}>Click me</div> <div on:click={() => alert('Clicked!')}>Click me too</div>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Inline event handlers duplicated | No extra nodes but multiple listeners | 0 reflows | Low paint cost | [!] OK |
| Reusable action attached to elements | No extra nodes, single reusable listener logic | 0 reflows | Low paint cost | [OK] Good |
actions in Svelte?tooltip on a button element in Svelte?use:actionName on elements.use:tooltip matches the correct syntax; others are for events or bindings.function highlight(node) {
node.style.backgroundColor = 'yellow';
return {
destroy() {
node.style.backgroundColor = '';
}
};
}function focus(node) {
node.focus();
}
<input use:focus />Pass the test and this pattern moves unknown