Performance: Action parameters
This affects how efficiently event handlers and DOM manipulations run during user interactions.
function myAction(node, param) { node.textContent = param; return { update(newParam) { if (newParam !== param) { param = newParam; node.textContent = param; } } }; } <div use:myAction="hello"></div>
function myAction(node) { return { update(param) { node.textContent = param; } }; } <div use:myAction="hello"></div>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Update DOM on every param change (no check) | Multiple DOM writes | Triggers reflow each update | Higher paint cost | [X] Bad |
| Update DOM only on param change | Minimal DOM writes | Reflow only when needed | Lower paint cost | [OK] Good |
use:action={parameter}?use:action={parameter}color with value 'red' to a Svelte action called highlight?use:action={parameter} where parameter can be any value or object.color and value 'red', use {color: 'red'} inside curly braces.function border(node, { color }) {
node.style.border = `2px solid ${color}`;
return {
update({ color }) {
node.style.border = `2px solid ${color}`;
}
};
}<div use:border={{ color: 'blue' }}>Box</div>function scale(node, factor) {
node.style.transform = `scale(${factor})`;
return {
update(newFactor) {
node.style.transform = `scale(${newFactor})`;
}
};
}use:scale={...}?factor, not an object.{ factor: 2 }, which will cause scale(${newFactor}) to become scale([object Object]), an invalid CSS transform value.tooltip that shows a message passed as a parameter and updates the message if it changes. Which of these implementations correctly handles parameter updates?function tooltip(node, message) {
const tip = document.createElement('span');
tip.textContent = message;
node.appendChild(tip);
return {
update(newMessage) {
tip.textContent = newMessage;
},
destroy() {
node.removeChild(tip);
}
};
} defines an update method that updates the tooltip text when the parameter changes.destroy method to remove the tooltip element when the action is removed, which is good practice.update and destroy methods -> Option DPass the test and this pattern moves unknown