javascript / expert
Snippet
Defensive Memory Management for Global Event Listeners
In Svelte 5, $effect is the primary tool for side effects. When binding to global objects like 'window' or 'document', returning a cleanup function is mandatory to prevent memory leaks during component unmounting or reactive re-executions.
snippet.js
1
2
3
4
5
6
7
8
9
$effect(() => {const handleResize = () => {console.log('Window resized');};window.addEventListener('resize', handleResize);return () => {window.removeEventListener('resize', handleResize);};});
svelte
Breakdown
1
$effect(() => {
Registers a reactive side effect that runs after DOM updates.
2
window.addEventListener('resize', handleResize);
Attaches a listener to the global window object.
3
return () => { ... };
Crucial cleanup pattern: Svelte executes this function before the effect re-runs or when the component is destroyed.