Named actions let you add reusable behavior to HTML elements in Svelte. They help keep your code clean and easy to understand.
Named actions in Svelte
function actionName(node, parameters) { // setup code here return { update(newParameters) { // handle parameter changes }, destroy() { // cleanup code here } }; } <!-- Use in markup --> <div use:actionName={parameters}></div>
The node is the HTML element the action is applied to.
The function can return an object with update and destroy to handle changes and cleanup.
function focus(node) { node.focus(); return { destroy() { // no cleanup needed here } }; } <!-- Usage --> <input use:focus>
function highlight(node, color = 'yellow') { node.style.backgroundColor = color; return { update(newColor) { node.style.backgroundColor = newColor; }, destroy() { node.style.backgroundColor = ''; } }; } <!-- Usage --> <p use:highlight={'lightblue'}>Text with highlight</p>
This named action adds a tooltip that appears when you hover over the button. It cleans up the tooltip when the mouse leaves or the element is removed.
<script> function tooltip(node, text) { let div; function mouseOver() { div = document.createElement('div'); div.textContent = text; div.style.position = 'absolute'; div.style.background = 'black'; div.style.color = 'white'; div.style.padding = '0.25rem 0.5rem'; div.style.borderRadius = '0.25rem'; div.style.top = `${node.getBoundingClientRect().bottom + window.scrollY + 5}px`; div.style.left = `${node.getBoundingClientRect().left + window.scrollX}px`; document.body.appendChild(div); } function mouseOut() { if (div) { div.remove(); div = null; } } node.addEventListener('mouseover', mouseOver); node.addEventListener('mouseout', mouseOut); return { update(newText) { text = newText; }, destroy() { node.removeEventListener('mouseover', mouseOver); node.removeEventListener('mouseout', mouseOut); if (div) div.remove(); } }; } </script> <button use:tooltip={'Click me to do something'}>Hover me</button>
Always clean up event listeners or DOM changes in the destroy method to avoid memory leaks.
You can update the action's behavior by using the update method when parameters change.
Named actions help keep your components tidy by moving behavior outside the markup.
Named actions add reusable behavior to HTML elements in Svelte.
They receive the element and optional parameters, and can clean up after themselves.
Use them to keep your code organized and avoid repeating logic.
Practice
Solution
Step 1: Understand what named actions do
Named actions in Svelte are used to add behavior to HTML elements that can be reused across components.Step 2: Compare with other options
Defining components, styling, and state management are handled differently in Svelte, not by named actions.Final Answer:
To add reusable behavior to HTML elements -> Option CQuick Check:
Named actions = reusable element behavior [OK]
- Confusing actions with components
- Thinking actions handle styling
- Assuming actions manage state
Solution
Step 1: Recall named action syntax
Named actions are functions that receive the element node as the first argument, typically declared asfunction myAction(node) {}.Step 2: Check other options
Arrow functions can work but must return an object for cleanup; action myAction(node) { /* code */ } uses invalid syntax.Final Answer:
function myAction(node) { /* code */ } -> Option AQuick Check:
Named action = function with node parameter [OK]
- Using invalid 'action' keyword
- Defining without node parameter
- Using arrow function without return object
function highlight(node) {
node.style.backgroundColor = 'yellow';
return {
destroy() {
node.style.backgroundColor = '';
}
};
}
<div use:highlight>Hello</div>What happens when the component is removed from the page?
Solution
Step 1: Understand the action's destroy method
The destroy method resets the background color to empty string when the element is removed.Step 2: Effect on component removal
When the component unmounts, destroy runs, so the background color resets to default.Final Answer:
The background color resets to default -> Option AQuick Check:
destroy resets styles on removal [OK]
- Assuming styles persist after removal
- Thinking destroy is optional
- Confusing destroy with element removal
function focus(node) {
node.focus();
return {
destroy() {
node.blur();
}
}
}
<input use:focus>Solution
Step 1: Analyze the focus call timing
Calling node.focus() immediately may not work reliably because the element might not be fully rendered, visible, or ready (e.g., during CSS transitions or animations).Step 2: Best practice for focus actions
In Svelte, it's often necessary to delay the focus call using tick(), requestAnimationFrame, or setTimeout(..., 0) to ensure DOM readiness.Final Answer:
The action should not call node.focus() immediately -> Option BQuick Check:
Delay focus with tick() or RAF [OK]
- Calling focus immediately without delay
- Ignoring DOM/transition timing issues
- Assuming focus always succeeds synchronously
Solution
Step 1: Understand parameter updates in named actions
Named actions can return an update function to handle parameter changes dynamically.Step 2: Evaluate options for handling parameter changes
Setting color once ignores updates; reactive statements inside action function don't track parameters; recreating action is inefficient.Final Answer:
Return an update function from the action that sets the color when parameters change -> Option DQuick Check:
Use update() to handle parameter changes [OK]
- Ignoring parameter updates
- Misusing reactive statements inside actions
- Recreating actions unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
