Learn Svelte Actions

An action is a function actionName(node, parameter) attached with use:actionName={parameter} and called once when its element enters the DOM, so it's safe to…

The "Search the menu..." box should be ready to type in the moment it shows up, without the customer clicking it first. For jobs that touch an element directly like this, Svelte has the action: a plain function Svelte calls when an element enters the DOM. You attach it to an element with use:actionName, and the function receives the element itself, so it can focus it, set an attribute, or listen for clicks.

Picture the bill clip at Mrs. Sri's stall. The same clip fits on any plate. When it goes on, the bill is clipped in. If the order changes, the paper is swapped. When the plate is cleared, the clip comes off so it isn't left lying on the table. The plate is the element, the bill is the parameter, and those three moments are attach, update and destroy.

A first action: autofocus

<script>
  function autofocus(node) {
    node.focus()
  }
</script>

<input use:autofocus placeholder="Search the menu..." />

The first exercise is exactly this: the starter already has the autofocus function, and you only put use:autofocus on the <input>.

Parameters and update: a total tooltip

An action can take one value: write use:tooltip={value}, and that value becomes the second argument. If the action returns an object with update and destroy, Svelte calls update whenever the value changes, and destroy when the element is removed.

<script>
  let icedTeaPortions = $state(3)

  let total = $derived(2 * 15 + 12 + icedTeaPortions * 5)

  function tooltip(node, text) {
    node.setAttribute("title", text)

    return {
      update(newText) {
        node.setAttribute("title", newText)
      },
      destroy() {
        node.removeAttribute("title")
      },
    }
  }
</script>

<button use:tooltip={"Total $" + total.toFixed(2)}>Cart (3)</button>
<button onclick={() => (icedTeaPortions += 1)}>+1 Iced Tea</button>

The cart is the one from the Animations lesson: Fried Rice x2, Chicken Noodles x1, Iced Tea x3. This is what Svelte 5 calls:

Event What gets called The Cart button's title
the button enters the DOM tooltip(button, "Total $57.00") Total $57.00
click +1 Iced Tea update("Total $62.00") Total $62.00
another variable changes nothing unchanged
the button is removed destroy() attribute removed

The second exercise builds this action yourself: tooltip(node, text) with setAttribute('title', text), attached with use:tooltip={'This is a tooltip'} on a <button>.

clickOutside: closing the cart dropdown

<script>
  let open = $state(false)

  function clickOutside(node, close) {
    function check(event) {
      if (!node.contains(event.target)) close()
    }
    // true: listen in the capture phase (explained below)
    document.addEventListener("click", check, true)

    return {
      update(newClose) {
        close = newClose
      },
      destroy() {
        document.removeEventListener("click", check, true)
      },
    }
  }
</script>

<button onclick={() => (open = true)}>Cart (3)</button>

{#if open}
  <div class="dropdown" use:clickOutside={() => (open = false)}>
    <p>Fried Rice x2</p>
    <p>Chicken Noodles x1</p>
    <p>Iced Tea x3</p>
  </div>
{/if}

destroy: remove what you add

Now destroy is deleted from clickOutside. This is what happens:

Event With destroy Without destroy
open 1 listener 1 listener
click outside, dropdown closes 0 listeners 1 listener, holding the old dropdown
open again 1 listener 2 listeners
click Fried Rice inside the dropdown stays open closes

The first listener is never removed, and it still holds the first dropdown's node, which has been thrown off the page. A dropdown that's been thrown away contains nothing that's on the page, so node.contains(event.target) is always false, and that old listener treats every click as a click outside. Even the click on Fried Rice calls close(). So the dropdown closes.

The problem piles up too: after three opens and closes, every click anywhere runs check three times at once. It's the same memory leak as the interval nobody stopped in the Lifecycle lesson. The rule: anything an action adds outside its own element (a listener on document or window, an interval, an observer) has to be removed in destroy.

Other options for new code. The update and destroy form above still works, and this lesson's exercises use it. The Svelte 5 docs now prefer these two:

$effect inside the action. Add the listener inside $effect, then return the function that removes it. Svelte runs that function when the element is removed, the same as destroy. Tested on Svelte 5.16 and 5.57: open, click outside, and the number of click listeners goes back to 0.

function clickOutside(node, close) {
  $effect(() => {
    function check(event) {
      if (!node.contains(event.target)) close()
    }
    document.addEventListener("click", check, true)
    return () => document.removeEventListener("click", check, true)
  })
}

Attachments, {@attach ...}, since Svelte 5.29. An attachment is a function that receives the element. The difference from an action: an attachment runs again whenever a value inside it changes, so it needs no update.

<script>
  function tooltip(text) {
    return (node) => {
      node.setAttribute("title", text)
      return () => node.removeAttribute("title")
    }
  }
</script>

<button {@attach tooltip("Total $" + total)}>Cart (3)</button>

Click +1 Iced Tea: the remove function deletes the old title, then tooltip is attached again with Total $62. An attachment can also go on a component, as long as the component passes its props on to an element with {...props}. The exercise editor uses Svelte 5.16, which doesn't know {@attach} yet: its compiler refuses it with Attribute shorthand cannot be empty.

Older code: Svelte 4

In Svelte 4 code, actions are written exactly the same: use:, update and destroy. Only what's around them differs: let icedTeaPortions = 3 without $state, $: total = ... for the derived value, and on:click on the button. An action that sends its own event, for example node.dispatchEvent(new CustomEvent("clickoutside")), was listened to with on:clickoutside={...} in Svelte 4. In Svelte 5, that event is listened to as an ordinary attribute: onclickoutside={...}.

⚠️ Actions that leak or sit in the wrong place

TL;DR: An action is a function actionName(node, parameter) attached with use:actionName={parameter} and called once when its element enters the DOM, so it's safe to use the DOM inside it: node.focus(), node.setAttribute("title", text), or a click listener. An action can return { update, destroy }: update(newValue) runs when the parameter changes, destroy() runs when the element is removed. Anything added outside the element has to be removed in destroy; without it, clickOutside listeners pile up and close a dropdown that was just opened. A document listener for clicks outside uses the capture phase (true), so the opening click doesn't close it straight away. Actions are for HTML elements only, not components. State used in the parameter is made with $state, and an event an action sends is listened to as an attribute, such as onclickoutside={...}. The exercises: <input use:autofocus />, then <button use:tooltip={'This is a tooltip'}>Hover me</button>.

⚡ use: calls a function when the element enters

Write:

<script>
  function autofocus(node) {
    node.focus()
  }
</script>

<input use:autofocus placeholder="Search the menu..." />

Meaning: use:autofocus tells Svelte to call autofocus(node) once, right after the <input> enters the DOM. node is the element itself, so it's safe to use the DOM inside it.

⚡ Parameter, update and destroy

Write:

<script>
  function tooltip(node, text) {
    node.setAttribute("title", text)

    return {
      update(newText) {
        node.setAttribute("title", newText)
      },
      destroy() {
        node.removeAttribute("title")
      },
    }
  }
</script>

<button use:tooltip={"Total $" + total.toFixed(2)}>Cart (3)</button>

Meaning: The value in use:tooltip={...} becomes the second argument. update is called whenever that value changes, and destroy when the element is removed.

⚡ Remove what you add

Guess first: destroy is deleted from clickOutside. The dropdown is opened, closed, opened again, then Fried Rice inside it is clicked. Does the dropdown stay open?

No, it closes. The first listener is never removed and still holds the old dropdown that was thrown away, so every click counts as a click outside.

Meaning: Anything an action adds outside its own element, such as a listener on document, has to be removed in destroy.

What you will learn