0
0
Svelteframework~8 mins

Action with event dispatching in Svelte - Performance & Optimization

Choose your learning style9 modes available
Performance: Action with event dispatching
MEDIUM IMPACT
This affects interaction responsiveness and event handling efficiency in the browser.
Handling user interaction with a custom action that dispatches events
Svelte
function myAction(node) {
  const handleClick = () => {
    node.dispatchEvent(new CustomEvent('myEvent', { detail: { clicked: true } }));
  };
  node.addEventListener('click', handleClick);
  return {
    destroy() {
      node.removeEventListener('click', handleClick);
    }
  };
}
Reuses the same function reference for adding and removing event listeners, preventing memory leaks.
📈 Performance GainReduces memory usage and avoids unnecessary event listener buildup.
Handling user interaction with a custom action that dispatches events
Svelte
function myAction(node) {
  node.addEventListener('click', () => {
    node.dispatchEvent(new CustomEvent('myEvent', { detail: { clicked: true } }));
  });
  return {
    destroy() {
      node.removeEventListener('click', () => {});
    }
  };
}
Creates a new anonymous function for event listener removal, causing the listener not to be removed and potential memory leaks.
📉 Performance CostLeads to increased memory usage and potential slowdowns on long-lived pages.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Anonymous event listener in actionNo extra DOM nodes0 reflowsMinimal paint[X] Bad
Named event listener with proper cleanupNo extra DOM nodes0 reflowsMinimal paint[OK] Good
Rendering Pipeline
Event dispatching in actions triggers the browser's event system without forcing layout recalculations unless DOM changes occur.
Event Handling
Composite
⚠️ BottleneckEvent Handling when many listeners or inefficient dispatching occurs
Core Web Vital Affected
INP
This affects interaction responsiveness and event handling efficiency in the browser.
Optimization Tips
1Always use named functions for event listeners to enable proper cleanup.
2Avoid DOM mutations during event dispatch to prevent layout thrashing.
3Keep event handlers lightweight to maintain fast interaction responsiveness.
Performance Quiz - 3 Questions
Test your performance knowledge
Why should you use a named function for event listeners in Svelte actions?
ATo reduce the size of the JavaScript bundle.
BTo ensure the event listener can be properly removed, preventing memory leaks.
CBecause anonymous functions run slower in the browser.
DTo make the code look cleaner.
DevTools: Performance
How to check: Record a performance profile while interacting with the element using the action. Look for event handler execution time and memory usage.
What to look for: Low event handler execution time and no increasing memory usage over repeated interactions indicate good performance.