0
0
SvelteHow-ToBeginner · 4 min read

How to Use use: Directive in Svelte for Actions

In Svelte, the use: directive applies an action to an element, letting you run custom code when the element is created or updated. You define an action as a function that receives the element and optionally returns a cleanup function. Use it like <div use:actionName> to enhance element behavior.
📐

Syntax

The use: directive attaches an action to an element. An action is a function that receives the element as its first argument and optionally returns an object with a destroy method for cleanup.

Syntax parts:

  • use:actionName: applies the action called actionName to the element.
  • Action function: function actionName(node) { ... } where node is the element.
  • Optional cleanup: return { destroy() { ... } } to run code when the element is removed.
javascript
function actionName(node) {
  // code to run when element is created
  return {
    destroy() {
      // code to run when element is removed
    }
  };
}

// Usage in markup:
// <div use:actionName></div>
💻

Example

This example shows a use:tooltip action that adds a simple tooltip to an element on mouse hover.

svelte
<script>
  function tooltip(node, text) {
    let tooltipDiv;

    function mouseOver() {
      tooltipDiv = document.createElement('div');
      tooltipDiv.textContent = text;
      tooltipDiv.style.position = 'absolute';
      tooltipDiv.style.background = 'black';
      tooltipDiv.style.color = 'white';
      tooltipDiv.style.padding = '0.25rem 0.5rem';
      tooltipDiv.style.borderRadius = '0.25rem';
      tooltipDiv.style.top = node.getBoundingClientRect().bottom + window.scrollY + 'px';
      tooltipDiv.style.left = node.getBoundingClientRect().left + window.scrollX + 'px';
      document.body.appendChild(tooltipDiv);
    }

    function mouseOut() {
      if (tooltipDiv) {
        tooltipDiv.remove();
        tooltipDiv = null;
      }
    }

    node.addEventListener('mouseover', mouseOver);
    node.addEventListener('mouseout', mouseOut);

    return {
      destroy() {
        node.removeEventListener('mouseover', mouseOver);
        node.removeEventListener('mouseout', mouseOut);
        if (tooltipDiv) tooltipDiv.remove();
      }
    };
  }
</script>

<button use:tooltip={'Click me!'}>Hover me</button>
Output
A button labeled 'Hover me' that shows a black tooltip with white text 'Click me!' below it when hovered.
⚠️

Common Pitfalls

Common mistakes when using use: directive include:

  • Not returning a destroy method to clean up event listeners or DOM changes, causing memory leaks.
  • Forgetting to handle updates if the action depends on parameters (use the second argument and return an update method).
  • Using use: on elements that are conditionally removed without cleanup.
javascript
/* Wrong: no cleanup, event listener stays after element removal */
function badAction(node) {
  node.addEventListener('click', () => alert('Clicked!'));
}

/* Right: cleanup event listener on destroy */
function goodAction(node) {
  function onClick() {
    alert('Clicked!');
  }
  node.addEventListener('click', onClick);
  return {
    destroy() {
      node.removeEventListener('click', onClick);
    }
  };
}
📊

Quick Reference

use: directive cheat sheet

PartDescription
use:actionAttach action function to element
Action functionReceives element node, runs setup code
Return objectOptional destroy() for cleanup
ParametersSecond argument to action for dynamic data
update()Optional method to handle parameter changes
PartDescription
use:actionAttach action function to element
Action functionReceives element node, runs setup code
Return objectOptional destroy() for cleanup
ParametersSecond argument to action for dynamic data
update()Optional method to handle parameter changes

Key Takeaways

The use: directive applies custom actions to elements for enhanced behavior.
Actions receive the element node and can return a destroy method for cleanup.
Always clean up event listeners or DOM changes in the destroy method.
Use the second argument and update method to handle dynamic parameters.
The use: directive helps keep element behavior modular and reusable.