0
0
Svelteframework~5 mins

Action update and destroy in Svelte

Choose your learning style9 modes available
Introduction

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.

When you want to run code every time the element's parameters change.
When you need to clean up event listeners or timers when the element is removed.
When you want to keep external libraries or plugins in sync with your element.
When you want to manage resources efficiently and avoid memory leaks.
Syntax
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.

Examples
This action changes the background color of an element and updates it when the color changes. It also resets the color when the element is removed.
Svelte
function highlight(node, color) {
  node.style.backgroundColor = color;

  return {
    update(newColor) {
      node.style.backgroundColor = newColor;
    },
    destroy() {
      node.style.backgroundColor = '';
    }
  };
}
This action logs clicks on the element and cleans up the event listener when the element is removed.
Svelte
function logClicks(node) {
  function handleClick() {
    console.log('Element clicked!');
  }
  node.addEventListener('click', handleClick);

  return {
    destroy() {
      node.removeEventListener('click', handleClick);
    }
  };
}
Sample Program

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.

Svelte
<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>
OutputSuccess
Important Notes

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.

Summary

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.