javascript / expert
Snippet
Manual Lifecycle Management with $effect.root
Normally, effects are tied to the component lifecycle. However, for global state or external library integrations, you might need effects that live outside Svelte components. $effect.root creates a non-tracked scope where effects can run indefinitely until the returned cleanup function is manually called. This is an advanced tool for managing 'zombie' effects and ensuring proper resource disposal in complex, non-component-based logic.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const cleanup = $effect.root(() => {$effect(() => {console.log('Global listener active:', appState.id);// Setup external subscriptionconst unsub = socket.subscribe(appState.id, (data) => {syncInternalState(data);});return () => unsub();});return () => {console.log('Root effect destroyed');};});// Later, to stop everything manually:// cleanup();
svelte
Breakdown
1
const cleanup = $effect.root(() => {
Initializes a root scope that allows creating effects outside of a component's lifecycle.
2
return () => unsub();
Standard effect cleanup that runs whenever 'appState.id' changes within the root.
3
cleanup();
Manually invoking this function destroys the root and all its internal effects, preventing memory leaks.