Discover how a tiny reusable trick can save you hours of repetitive coding!
Why Default actions in Svelte? - Purpose & Use Cases
Imagine you want to add the same behavior to many buttons on your webpage, like focusing an input when a button is clicked. You write the same event code over and over for each button.
Writing repetitive event handlers for each element is tiring and easy to forget. It clutters your code and makes updates slow because you must change every handler separately.
Svelte's default actions let you write reusable behaviors once and apply them easily to any element. This keeps your code clean and consistent without repeating yourself.
button.addEventListener('click', () => { input.focus(); });<button use:focusOnClick>Click me</button>
<script>
function focusOnClick(node) {
node.addEventListener('click', () => {
document.querySelector('input').focus();
});
return {
destroy() {
node.removeEventListener('click', () => {
document.querySelector('input').focus();
});
}
};
}
</script>It enables you to create simple, reusable behaviors that automatically attach to elements, making your app easier to build and maintain.
Think of a form where clicking any label focuses its input. Instead of coding each label separately, a default action can handle all labels uniformly.
Manual event handling is repetitive and error-prone.
Default actions let you write reusable behaviors once.
They keep your code clean and easy to update.
Practice
Solution
Step 1: Understand what default actions do
Default actions in Svelte run code when an element is created and can clean up when it is removed.Step 2: Match purpose with options
Only To add behavior to an element when it is created and clean up when removed describes adding behavior on creation and cleanup on removal, which matches default actions.Final Answer:
To add behavior to an element when it is created and clean up when removed -> Option AQuick Check:
Default actions add and clean behavior = B [OK]
- Confusing default actions with styling or data fetching
- Thinking default actions create components
- Assuming default actions only run once globally
focus to an input element in Svelte?Solution
Step 1: Recall Svelte default action syntax
Default actions are applied usinguse:actionNameon elements.Step 2: Compare options with correct syntax
<input use:focus />usesuse:focus, which is the correct way to apply the action.Final Answer:
<input use:focus /> -> Option DQuick Check:
Default action syntax = use:actionName [OK]
use: prefix to apply default actions [OK]- Using
action:oron:instead ofuse: - Confusing event handlers with actions
- Trying to bind actions like variables
function highlight(node) {
node.style.backgroundColor = 'yellow';
return {
destroy() {
node.style.backgroundColor = '';
}
};
}
<div use:highlight>Hello</div>What will be the background color of the <div> when it is rendered?
Solution
Step 1: Analyze the highlight action code
The action setsbackgroundColorto 'yellow' on the node when applied.Step 2: Understand the effect on the <div>
The <div> usesuse:highlight, so its background color becomes yellow on render.Final Answer:
Yellow -> Option AQuick Check:
Action sets background to yellow = A [OK]
- Thinking destroy runs immediately and clears color
- Confusing background color with text color
- Assuming no style changes without CSS
function logClick(node) {
node.addEventListener('click', () => console.log('Clicked!'));
}What is the main problem with this action?
Solution
Step 1: Check event listener management
The action adds a click listener but does not remove it on cleanup.Step 2: Understand Svelte action cleanup
Actions should return an object with adestroymethod to remove listeners and avoid memory leaks.Final Answer:
It does not remove the event listener when the element is removed -> Option CQuick Check:
Missing cleanup causes leaks = A [OK]
- Ignoring cleanup leads to memory leaks
- Thinking arrow functions are disallowed
- Assuming parentheses are required on use
autoFocus that focuses an input element when it appears and logs "Focused" once. Which code correctly implements this behavior?Solution
Step 1: Focus element and log once on mount
Callingnode.focus()and logging immediately runs once when the element appears.Step 2: Provide cleanup method
Returning an object with an emptydestroymethod is valid and ensures cleanup structure.Final Answer:
Function that focuses and logs once, with destroy method -> Option BQuick Check:
Focus and log once on mount = D [OK]
- Adding unnecessary event listeners for logging
- Missing return object with destroy method
- Logging multiple times on updates
Ready to prove it?
Pass the test and this pattern moves unknown
