| | |

Svelte 37 🧡 Element Lifecycles and DOM Manipulations with Actions (use:action)

⏱️ Estimated read: 7 min | |

Actions are Svelte’s answer to reusable DOM manipulation. While components are excellent for composing UI, they aren’t always the right tool for logic that attaches directly to an existing element—like initializing a third-party library, creating a custom tooltip, or setting up complex event listeners. Actions allow you to encapsulate this behavior into a single function, making it easily applicable to any element in your templates with a clean, declarative syntax.

This chapter covers the action lifecycle, the use: directive, and how to create and manage reusable DOM-level behaviors. We will explore the destroy hook for cleaning up memory and the update hook for responding to changes in data passed to the action, providing a robust pattern for enhancing HTML elements without bloating your component logic.

Key point: An action is a function that receives an element node, providing an entry point to its lifecycle where you can attach event listeners, initialize libraries, or manipulate the DOM, and crucially, return a destroy method to prevent memory leaks.


Why actions exist

The reusability gap.

Without actions, reusable DOM logic often ends up duplicated inside onMount hooks in different components. Actions centralize this logic into a single function that can be applied to any element in any component.

Direct DOM access.

Actions provide a direct reference to the node as soon as it is mounted. This is the most efficient way to interact with non-Svelte APIs, like Chart.js or D3, directly within the template.

Automatic cleanup.

The action lifecycle forces you to return a destroy function. This makes it impossible to forget to remove event listeners or clean up third-party instances, which is the primary cause of memory leaks in complex applications.

Declarative enhancements.

By applying logic via use:myAction, your template remains readable. It clearly signals that the element has “extra” behavior, such as being draggable or having a custom context menu, without cluttering the component’s internal logic.

Performance and scoping.

Actions run once when the element is created. They do not trigger re-renders of the component, making them much faster for high-frequency interactions compared to standard Svelte state-based UI updates.


a. The action lifecycle and signature

An action is a function that takes a DOM node and an optional parameters object. It can return an object containing an update function and a destroy function. The update function is called whenever the parameters passed to the action change, allowing the action to react to new data without being fully destroyed and recreated.

export function customAction(node, params) {
  // Initialization logic
  return {
    update(newParams) {
      // React to parameter changes
    },
    destroy() {
      // Cleanup event listeners/libraries
    }
  };
}

This structure is highly efficient. Because Svelte manages the lifecycle, you are guaranteed that destroy will run when the element is removed from the DOM, ensuring that event listeners or internal states are properly disposed of.

b. Applying actions with the use: directive

The use: directive applies an action to an element. You can pass parameters to the action, which Svelte will pass to the action’s initialization function and subsequently to the update hook. This makes actions highly dynamic and configurable from the template.

<script>
  import { tooltip } from './actions.js';
  let text = "Hover me!";
</script>

<button use:tooltip={text}>
  Hover for info
</button>

This is the standard pattern for declarative behavior. The action tooltip is applied to the button. If the text variable changes, Svelte automatically calls the update function inside the action, allowing the tooltip to reflect the new text without needing manual event listener updates.

c. Parameterized state and dynamic updates

Actions excel at handling configuration. When you provide an object to an action, you can pass multiple data points. The action can then decompose these parameters to configure the DOM node. If you pass an object, Svelte handles the reference checking, and the update function allows you to compare the old parameters with the new ones.

export function drag(node, { active }) {
  if (active) { /* enable drag */ }
  return {
    update({ active }) {
      if (active) { /* enable */ } else { /* disable */ }
    }
  };
}

This provides a clean interface for toggling behaviors. Instead of complex {#if} blocks wrapping elements to switch between states, you simply update the parameter passed to the action, and the action handles the internal node management.


Complete Example Session

// ============================================
// PART 1: A SIMPLE CLICK-OUTSIDE ACTION
// ============================================
export function clickOutside(node, callback) {
  const handleClick = (e) => {
    if (!node.contains(e.target)) callback();
  };
  document.addEventListener("click", handleClick);
  return {
    destroy: () => document.removeEventListener("click", handleClick)
  };
}

// ============================================
// PART 2: APPLYING THE ACTION
// ============================================
<script>
  import { clickOutside } from "./actions";
  let open = true;
</script>

{#if open}
  <div use:clickOutside={() => open = false}>
    Modal Content
  </div>
{/if}

// ============================================
// PART 3: ACTION WITH UPDATE LOGIC
// ============================================
export function highlight(node, color) {
  node.style.backgroundColor = color;
  return {
    update: (newColor) => node.style.backgroundColor = newColor
  };
}

// ============================================
// PART 4: DYNAMIC APPLICATION
// ============================================
<script>
  let color = "yellow";
</script>
<div use:highlight={color}>Dynamic Highlight</div>

These parts illustrate the core pattern: initialization in the function body, cleanup in destroy, and reactivity in update.


Quick Reference

Lifecycle Hooks

HookPurpose
initLogic running on mount
updateResponding to prop changes
destroyCleanup / Removal

Syntax

SyntaxUsage
use:actionApply without params
use:action={val}Apply with params
use:action={...}Pass object as params

Best Practices

✅ Do This:

// Always return destroy for listeners
return { destroy: () => removeEventListener(...) };           // ✅

// Use update to react to props
update: (p) => { node.textContent = p; }                      // ✅

// Keep actions focused and single-purpose
export function tooltip(node, text) { ... }                   // ✅

// Destructure params for clarity
update: ({ active }) => { ... }                               // ✅

❌ Don’t Do This:

// Forget to return destroy
return {}; // Risk of memory leak                           // ❌

// Use actions for complex data flow
// Use stores or components instead                         // ❌

// Over-engineer action internal state
// Keep it focused on the DOM                               // ❌

Common Pitfalls

PitfallWhy It HappensFix
Memory LeaksMissing destroyReturn destroy object
Ghost listenersListener never removedremoveEventListener in destroy
Sync issuesForgetting updateDefine update for dynamic params
Reactivity errorsMutating state directlyUse update parameters

Real-World Examples

1. Tooltip Attachment

<div use:tooltip={"Hello World"} />

2. Click Outside Detector

<div use:clickOutside={close} />

3. Focus Manager

<input use:focus />

4. Draggable Element

<div use:draggable />

5. Scroll Spy

<section use:scrollSpy={id} />

6. Long Press Handler

<button use:longpress={callback} />

7. Intersection Observer

<div use:inView={onEnter} />

8. Copy to Clipboard

<button use:copy={text} />

9. Auto-Resize Textarea

<textarea use:autoResize />

10. Swipe Gesture

<div use:swipe={handler} />

Visual

Action Lifecycle

┌──────────────────────────────────────────────┐
│  Template ──► use:action ──► Init (node)     │
│                                 │            │
│  Data Change ──► Update ◄───────┘            │
│                                 │            │
│  Element Removal ──► Destroy ◄──┘            │
└──────────────────────────────────────────────┘

Memory Management

┌──────────────────────────────────────────────┐
│  Action Init:  addEventListener              │
│  Action Destroy: removeEventListener         │
│                                              │
│  Result: No memory leaks, clean state        │
└──────────────────────────────────────────────┘

Summary

ItemValue
PurposeDOM Manipulation
LifecycleInit, Update, Destroy
Syntaxuse:action
ScopeElement-level
CleanupRequired (destroy)

Key takeaways:

  • Actions are for DOM-level logic. If you need to manipulate the DOM, attach listeners, or initialize a library, an action is more efficient than a component lifecycle hook.
  • Always clean up. Returning a destroy function is not optional; it is the fundamental mechanism that keeps your app from leaking memory.
  • Use update for reactivity. Actions can react to changes in data passed via props, keeping the element in sync with the component state.
  • Keep them reusable. Design your actions to be independent of specific component state, passing in parameters as arguments instead.
  • Declarative template. The use: directive maintains the clarity of your HTML structure while injecting complex behavior underneath.

Remember: Actions are the most powerful tool in the Svelte developer’s toolkit for DOM-specific behavior. By encapsulating logic, lifecycle management, and cleanup into a single, declarative interface, you create highly maintainable and performant UI enhancements that are easy to reuse across your entire project.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!