Svelte 38 ๐งก Action Parameters, Reactive Updates, and Cleanup Handlers
Actions in Svelte are more than just initialization hooks; they are powerful tools for synchronizing external data with the DOM. When you pass a parameter to an actionโlike an options object or a reactive valueโSvelte tracks these changes and orchestrates the updates through the action’s lifecycle. Understanding how to pass this data, respond to updates, and ensure total cleanup is critical for creating stable, production-grade custom behaviors.
This chapter dives deep into the mechanics of action parameters, the update lifecycle hook, and advanced cleanup strategies. We will examine how to efficiently handle dynamic data within your custom directives and ensure that your logic remains performant and bug-free as your application’s state changes.
Key point: The update hook is the bridge between your component’s reactive state and the imperative DOM manipulation within an action, while the destroy hook ensures that every event listener, interval, or library instance is cleanly removed, preventing memory leaks and ghost events.
Why action parameters and lifecycle hooks exist
The data-sync necessity.
Static actions are rarely sufficient. When you need to pass dynamic data (like a threshold value, a color string, or an API key), parameters allow the action to adapt to the component’s state, keeping the logic reusable and configuration-agnostic.
The update performance.
Without an update hook, you would have to destroy and re-initialize the action every time data changed, which is expensive and potentially destructive to the element’s state (like resetting an animation or scroll position). The update hook allows for granular, targeted DOM changes.
The memory safety requirement.
Dynamic actions often involve attaching global listeners or creating timers. The destroy hook ensures these global resources don’t persist after the componentโor the element itselfโhas been removed from the DOM.
Encapsulated logic.
By coupling parameters, updates, and cleanup into a single interface, you avoid “leaky abstractions” where the parent component needs to know too much about the internal implementation details of your DOM manipulation.
Predictive lifecycle.
Svelte guarantees the execution order: init runs once, update runs every time parameters change, and destroy runs exactly when the node is unmounted. This predictability is the foundation of building stable non-Svelte integrations (like maps or editors).
a. Handling and destructuring action parameters
An action’s initialization function receives the parameter you pass in the use: directive as its second argument. Whether you pass a primitive, an array, or an object, Svelte provides it ready for use. Destructuring these parameters directly in the function arguments makes your code cleaner and easier to reason about.
// A simple action that takes an object of options
export function settings(node, { color, size = '10px' }) {
node.style.color = color;
node.style.fontSize = size;
return {
update({ color: newColor, size: newSize }) {
node.style.color = newColor;
node.style.fontSize = newSize;
}
};
}
By defining defaults in the destructuring (like size = '10px'), you ensure that your action is robust against missing properties. Svelte ensures that if the object passed in the template changes, your update function is triggered with the new values.
b. The update lifecycle hook
The update hook is Svelte’s mechanism for reconciliation. It is only called if the parameter value changes (using reference equality checks). This is where you perform efficient DOM updatesโinstead of re-running setup logic, you only modify the specific style or property that changed.
export function logger(node, config) {
console.log("Initialized with:", config);
return {
update(newConfig) {
// Only runs when 'config' object reference changes
console.log("Updated to:", newConfig);
}
};
}
Note: If you pass an object to an action, ensure you are creating a new object reference in your component when updating (e.g., config = { ...config, val: 5 }). If you mutate the existing object, Svelte may not detect the change, and the update hook will not fire.
c. Advanced cleanup patterns
Cleanup is not limited to simple event listeners. Advanced cleanup might involve closing socket connections, clearing setInterval timers, or destroying third-party plugin instances (like a date picker or chart instance). The destroy hook is the final safeguard against memory bloat.
export function liveTimer(node, interval) {
let timer = setInterval(() => {
node.textContent = new Date().toLocaleTimeString();
}, interval);
return {
destroy() {
// Clean up the timer to prevent memory leaks
clearInterval(timer);
}
};
}
For complex cleanup, you can use a scoped object or class within your action to manage resources. The destroy function provides a clean scope to access these objects, ensuring that everything is disposed of regardless of how the component was closed.
Complete Example Session
// ============================================
// PART 1: ACTION SETUP WITH PARAMETERS
// ============================================
export function highlight(node, { color = "yellow", bold = false }) {
const apply = (c, b) => {
node.style.backgroundColor = c;
node.style.fontWeight = b ? "bold" : "normal";
};
apply(color, bold);
// ============================================
// PART 2: THE UPDATE HOOK
// ============================================
return {
update({ color: newColor, bold: newBold }) {
apply(newColor, newBold);
},
// ============================================
// PART 3: CLEANUP
// ============================================
destroy() {
node.style.backgroundColor = "";
node.style.fontWeight = "";
}
};
}
This sequence provides a complete pattern: initial application, reactive updates, and a clean teardown that resets the element’s styles.
Quick Reference
The Action API
| Hook | Arguments | Execution Frequency |
|---|---|---|
init | (node, params) | Once on mount |
update | (newParams) | On param change |
destroy | N/A | On unmount |
Parameter Patterns
| Pattern | Best For |
|---|---|
| Object | Complex configuration |
| Primitive | Simple state toggles |
| Function | Callbacks / Events |
Best Practices
โ Do This:
// Destructure parameters for cleaner access
export function action(node, { mode }) { ... } // โ
// Always update styles/state only in update()
update: (p) => { node.style.color = p.color; } // โ
// Create new object references for reactive triggers
params = { ...params, color: 'blue' }; // โ
// Return empty object if no cleanup is needed
return {}; // โ
โ Don’t Do This:
// Mutate objects passed as parameters
params.color = 'red'; // Won't trigger update // โ
// Use global variables inside actions
// Keep state inside the action function scope // โ
// Ignore the update() hook for dynamic logic
// Re-running everything in the init() // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Update not firing | Object mutation | Create new object reference |
| Resource leak | Missing destroy | Return cleanup function |
| Stale closure | Referring to old props | Use updated params argument |
| Logic drift | init and update duplicated | Extract shared function |
Real-World Examples
1. Dynamic Tooltip
<button use:tooltip={{ text, delay: 500 }} />
2. Debounced Resize
<div use:resize={{ onResize, debounce: 200 }} />
3. Theme Injection
<section use:theme={{ colors, mode }} />
4. Progress Tracking
<div use:progress={{ percent }} />
5. Custom Event Listener
<div use:listen={{ type: 'scroll', handler }} />
6. Animated Reveal
<div use:reveal={{ trigger: isVisible }} />
7. Input Masking
<input use:mask={{ format: 'phone' }} />
8. Live Stats
<span use:counter={{ start: 0, end: 100 }} />
9. Chart Update
<canvas use:chart={data} />
10. Map Marker Position
<div use:marker={{ lat, lng }} />
Visual
Data Flow in Action
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Component State โโโบ Parameters โโโบ Update โ
โ โ โ
โ Action Initialization โโโโโโโโโโโโโโโ โ
โ โผ โ
โ DOM Manipulation โโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Lifecycle Teardown
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Element Unmounted โโโบ Destroy Hook โ
โ โ โ
โ Action Logic โโโโโโโโโโโโ โ
โ - clearInterval() โ
โ - removeEventListener() โ
โ - dispose() โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Initialization | init(node, params) |
| Reactive Hook | update(newParams) |
| Teardown Hook | destroy() |
| Param detection | Reference equality |
| Cleanup | Mandatory for side-effects |
Key takeaways:
- Parameters drive reactivity. Actions respond to data changes through the
updatehook, which triggers only when the parameter reference changes. - Object references matter. Because Svelte uses reference equality for updates, always create new objects when updating parameters.
- Cleanup is a contract. The
destroyhook is your only chance to clean up global side effects; never assume the browser will garbage collect listeners/timers automatically. - Keep update logic minimal. Only change what is necessary in the
updatehook to keep DOM thrashing to a minimum. - Actions are highly encapsulated. They are the ideal way to bridge imperative DOM logic with declarative Svelte state.
Remember: Mastering action parameters and lifecycle hooks is the difference between a simple helper function and a robust, reusable DOM enhancement. By leveraging the update hook for reactivity and the destroy hook for safety, you ensure your custom DOM behaviors are reliable, performant, and leak-free.
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!