Bird
Raised Fist0
Svelteframework~10 mins

Named actions in Svelte - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Named actions
Define named action function
↓
Export action for use
↓
Use action in component element
↓
Svelte calls action with element
↓
Action runs setup code
↓
Optionally return cleanup function
↓
On element removal, cleanup runs
This flow shows how a named action is defined, exported, used on an element, and how Svelte runs setup and cleanup code.
Execution Sample
Svelte
export function highlight(node) {
  node.style.backgroundColor = 'yellow';
  return {
    destroy() { node.style.backgroundColor = ''; }
  };
}

// In component:
// <p use:highlight>Text</p>
This code defines a named action that highlights an element's background yellow and cleans up by removing the highlight when the element is removed.
Execution Table
StepActionInputEffect on ElementReturn Value
1Define named action 'highlight'node (element)No immediate effectFunction ready to use
2Export 'highlight' for component useN/ANo effectFunction available for import
3Use action on <p> element<p> element passed as nodeSvelte calls highlight(node)Object with destroy method returned
4Action runs setup codenode.style.backgroundColor = 'yellow'Element background becomes yellowSame object returned
5Element removed from DOMdestroy() calledBackground color reset to ''Cleanup done
6No more referencesN/AElement normalAction lifecycle ends
💡 Element removed, destroy cleanup runs, action lifecycle ends
Variable Tracker
VariableStartAfter Step 3After Step 4After Step 5Final
node.style.backgroundColor'' (empty)'' (before action runs)'yellow''' (after destroy runs)'' (final)
highlight return valueundefinedObject with destroy methodSame objectSame objectSame object
Key Moments - 3 Insights
Why does the background color change only after the action is used on the element?
Because the action function runs only when Svelte calls it with the element (see execution_table step 4). Defining or exporting the function alone does not affect the element.
What happens if the element using the action is removed from the page?
Svelte calls the destroy method returned by the action (execution_table step 5), which cleans up by resetting the background color.
Can the action return something other than a destroy method?
Yes, but for cleanup Svelte expects an object with a destroy method. Without it, no cleanup runs (see execution_table step 5).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the background color of the element after step 4?
A'yellow'
B'' (empty string)
C'blue'
D'red'
💡 Hint
Check the 'Effect on Element' column at step 4 in the execution_table.
At which step does the cleanup code run to reset the background color?
AStep 3
BStep 5
CStep 4
DStep 6
💡 Hint
Look for when 'destroy() called' and background reset happens in the execution_table.
If the action did not return a destroy method, what would happen when the element is removed?
ABackground color resets automatically
BAction runs again
CBackground color stays yellow
DError is thrown
💡 Hint
Refer to key_moments about cleanup and destroy method necessity.
Concept Snapshot
Named actions in Svelte:
- Define a function receiving the element (node).
- Modify the element inside the function.
- Return an object with optional destroy() for cleanup.
- Use the action in markup with use:actionName.
- Svelte calls destroy() when element is removed.
Full Transcript
Named actions in Svelte let you run code on elements when they appear in the page and clean up when they leave. You write a function that takes the element as input, changes it (like setting background color), and returns an object with a destroy method to undo changes. In the component, you use this action with use:actionName on an element. When Svelte renders the element, it calls your action function. When the element is removed, Svelte calls destroy to clean up. This helps keep your UI interactive and tidy.

Practice

(1/5)
1. What is the main purpose of named actions in Svelte?
easy
A. To style elements with CSS
B. To define new components
C. To add reusable behavior to HTML elements
D. To manage application state

Solution

  1. 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.
  2. Step 2: Compare with other options

    Defining components, styling, and state management are handled differently in Svelte, not by named actions.
  3. Final Answer:

    To add reusable behavior to HTML elements -> Option C
  4. Quick Check:

    Named actions = reusable element behavior [OK]
Hint: Named actions add behavior to elements, not styles or state [OK]
Common Mistakes:
  • Confusing actions with components
  • Thinking actions handle styling
  • Assuming actions manage state
2. Which of the following is the correct syntax to define a named action in Svelte?
easy
A. function myAction(node) { /* code */ }
B. const myAction = () => { /* code */ }
C. let myAction = node => { /* code */ }
D. action myAction(node) { /* code */ }

Solution

  1. Step 1: Recall named action syntax

    Named actions are functions that receive the element node as the first argument, typically declared as function myAction(node) {}.
  2. Step 2: Check other options

    Arrow functions can work but must return an object for cleanup; action myAction(node) { /* code */ } uses invalid syntax.
  3. Final Answer:

    function myAction(node) { /* code */ } -> Option A
  4. Quick Check:

    Named action = function with node parameter [OK]
Hint: Named actions are functions with node parameter, not keywords [OK]
Common Mistakes:
  • Using invalid 'action' keyword
  • Defining without node parameter
  • Using arrow function without return object
3. Given this named action and usage:
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?
medium
A. The background color resets to default
B. The element is removed from the DOM immediately
C. An error occurs because destroy is missing
D. The background color stays yellow

Solution

  1. Step 1: Understand the action's destroy method

    The destroy method resets the background color to empty string when the element is removed.
  2. Step 2: Effect on component removal

    When the component unmounts, destroy runs, so the background color resets to default.
  3. Final Answer:

    The background color resets to default -> Option A
  4. Quick Check:

    destroy resets styles on removal [OK]
Hint: Destroy cleans up styles when element is removed [OK]
Common Mistakes:
  • Assuming styles persist after removal
  • Thinking destroy is optional
  • Confusing destroy with element removal
4. What is wrong with this named action code?
function focus(node) {
  node.focus();
  return {
    destroy() {
      node.blur();
    }
  }
}

<input use:focus>
medium
A. Calling node.blur() in destroy may cause errors if node is removed
B. The action should not call node.focus() immediately
C. The action does not return an object
D. The action must be async to work properly

Solution

  1. 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).
  2. 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.
  3. Final Answer:

    The action should not call node.focus() immediately -> Option B
  4. Quick Check:

    Delay focus with tick() or RAF [OK]
Hint: Delay node.focus() with tick() for reliability [OK]
Common Mistakes:
  • Calling focus immediately without delay
  • Ignoring DOM/transition timing issues
  • Assuming focus always succeeds synchronously
5. You want to create a named action that changes an element's text color based on a parameter and updates it when the parameter changes. Which approach is correct?
hard
A. Use a reactive statement inside the action function to watch parameters
B. Set the color once in the action and ignore parameter changes
C. Recreate the action every time parameters change instead of updating
D. Return an update function from the action that sets the color when parameters change

Solution

  1. Step 1: Understand parameter updates in named actions

    Named actions can return an update function to handle parameter changes dynamically.
  2. 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.
  3. Final Answer:

    Return an update function from the action that sets the color when parameters change -> Option D
  4. Quick Check:

    Use update() to handle parameter changes [OK]
Hint: Use update() function to react to parameter changes [OK]
Common Mistakes:
  • Ignoring parameter updates
  • Misusing reactive statements inside actions
  • Recreating actions unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard