Actions in Svelte let you add behavior to HTML elements easily. The update and destroy functions help manage changes and cleanup when the element or data changes.
Action update and destroy in Svelte
function myAction(node, parameters) { // setup code here return { update(newParameters) { // code to run when parameters change }, destroy() { // cleanup code here } }; }
The node is the HTML element the action is applied to.
The update function runs when the parameters passed to the action change.
function highlight(node, color) { node.style.backgroundColor = color; return { update(newColor) { node.style.backgroundColor = newColor; }, destroy() { node.style.backgroundColor = ''; } }; }
function logClicks(node) { function handleClick() { console.log('Element clicked!'); } node.addEventListener('click', handleClick); return { destroy() { node.removeEventListener('click', handleClick); } }; }
This Svelte component uses an action called colorAction to change the text color of a paragraph. When you click the button, the color toggles between blue and red. The update function changes the color when currentColor changes. The destroy function resets the color if the paragraph is removed.
<script> function colorAction(node, color) { node.style.color = color; return { update(newColor) { node.style.color = newColor; }, destroy() { node.style.color = ''; } }; } let currentColor = 'blue'; function changeColor() { currentColor = currentColor === 'blue' ? 'red' : 'blue'; } </script> <button on:click={changeColor}>Toggle Color</button> <p use:colorAction={currentColor}>This text changes color when you click the button.</p>
Always clean up in destroy to avoid memory leaks.
The update function is optional but useful when parameters change.
Actions can be reused on many elements with different parameters.
Actions add behavior to elements with setup, update, and cleanup.
update runs when parameters change.
destroy runs when the element is removed to clean up.
Practice
destroy function in a Svelte action?Solution
Step 1: Understand the role of
Thedestroyin Svelte actionsdestroyfunction is called when the element using the action is removed from the DOM to clean up any side effects or event listeners.Step 2: Differentiate from other lifecycle functions
updatehandles parameter changes, and initialization happens in the main action function, not indestroy.Final Answer:
To clean up resources when the element is removed from the DOM -> Option CQuick Check:
destroy cleans up on removal = A [OK]
- Confusing destroy with update
- Thinking destroy initializes the action
- Assuming destroy runs on parameter change
update and destroy function from a Svelte action?Solution
Step 1: Recall the Svelte action return structure
A Svelte action returns an object with optionalupdateanddestroymethods as properties.Step 2: Match the correct syntax
return { update: (params) => {}, destroy: () => {} }; correctly returns an object withupdateanddestroyas arrow functions. Other options use invalid syntax or wrong property names.Final Answer:
return { update: (params) => {}, destroy: () => {} }; -> Option BQuick Check:
Return object with update and destroy keys = B [OK]
- Using arrays instead of objects
- Wrong function syntax inside return
- Using incorrect property names like onUpdate
function highlight(node, color) {
node.style.backgroundColor = color;
return {
update(newColor) {
node.style.backgroundColor = newColor;
},
destroy() {
node.style.backgroundColor = '';
}
};
}What happens when the action's parameter changes from 'yellow' to 'lightblue'?
Solution
Step 1: Understand the update function role
Theupdatemethod runs when the action's parameter changes, here it sets the background color to the new value.Step 2: Trace the parameter change effect
Changing from 'yellow' to 'lightblue' triggersupdate, which setsnode.style.backgroundColorto 'lightblue'.Final Answer:
The background color changes to 'lightblue' -> Option AQuick Check:
Parameter change triggers update = D [OK]
- Thinking destroy runs on parameter change
- Assuming update does nothing
- Confusing initial setup with update
function logClicks(node) {
function handleClick() {
console.log('Clicked');
}
node.addEventListener('click', handleClick);
return {
update() {
node.removeEventListener('click', handleClick);
}
};
}Solution
Step 1: Analyze the event listener management
The action adds a click listener but does not clean it up when the element is removed.Step 2: Check lifecycle methods usage
There is nodestroymethod to remove the listener on element removal, which can cause memory leaks.Final Answer:
The destroy function is missing to remove the event listener on element removal -> Option DQuick Check:
Missing destroy cleanup = C [OK]
- Removing listeners in update instead of destroy
- Not removing listeners at all
- Confusing update with destroy lifecycle
update and destroy?Solution
Step 1: Check update function correctness
Theupdatemethod should take anewColorparameter and setnode.style.color = newColor.Step 2: Verify destroy function behavior
Thedestroymethod shouldconsole.log('Element removed').Final Answer:
function colorText(node, color) { node.style.color = color; return { update(newColor) { node.style.color = newColor; }, destroy() { console.log('Element removed'); } }; } -> Option AQuick Check:
Update changes color, destroy logs message = A [OK]
- Updating wrong style property
- Missing destroy method
- Destroy resets style instead of logging
Ready to prove it?
Pass the test and this pattern moves unknown
