Performance: Named actions
Named actions affect how efficiently DOM elements are enhanced with behavior, impacting interaction responsiveness and layout stability.
function focus(node, params) { if (params?.shouldFocus) { node.focus(); } return { update(params) { if (params?.shouldFocus) { node.focus(); } } }; } // Usage in component <input use:focus={{ shouldFocus: true }} />
function focus(node) { node.focus(); return { update() { node.focus(); } }; } // Usage in component (with frequently changing param) <input use:focus={counter} /> <!-- counter changes frequently, triggering update every time -->
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Unconditional focus on update | Multiple focus calls | Multiple reflows per update | High paint cost due to layout shifts | [X] Bad |
| Conditional focus only when needed | Single focus call | Single reflow on initial focus | Low paint cost, stable layout | [OK] Good |
function myAction(node) {}.function highlight(node) {
node.style.backgroundColor = 'yellow';
return {
destroy() {
node.style.backgroundColor = '';
}
};
}
<div use:highlight>Hello</div>function focus(node) {
node.focus();
return {
destroy() {
node.blur();
}
}
}
<input use:focus>Pass the test and this pattern moves unknown