Svelte 37: Custom Actions Deep Dive
easy⏱ 5 mincoursesvelte
The three lifecycle hooks of an action
The action function itself runs once, when the node is first mounted — that's where you do one-time setup like attaching listeners. The optional update(newParams) runs on every subsequent change to the use:action={params} expression, without tearing anything down. The optional destroy() runs exactly once, right before Svelte removes the node from the DOM.
function myAction(node, params) {
// runs once, on mount
return {
update(newParams) { /* params changed */ },
destroy() { /* node is being removed */ }
};
}
Skipping destroy() is a real memory leak
Anything an action attaches outside the node itself — a document/window listener, a manually-created element like our tooltip bubble, a third-party library instance — will outlive the component unless destroy() explicitly tears it down. Svelte can't clean up what it doesn't know about.
Build the live-updating tooltip
Implement tooltip(node, text) with mount, update, and destroy, apply it with use:tooltip={...} on a button whose tooltip text depends on a counter, then toggle the button's own visibility to prove destroy() actually runs.