javascript / expert
Snippet
Circular Dependency Mitigation with untrack
In Svelte 5, effects automatically subscribe to all reactive state read during execution. When you need to read a value without creating a subscription—often to prevent infinite loops or unnecessary re-runs—the untrack function isolates the execution context.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
let count = $state(0);let status = $state('normal');$effect(() => {if (count > 10) {const currentStatus = untrack(() => status);if (currentStatus !== 'alert') status = 'alert';}});
svelte
Breakdown
1
untrack(() => status)
Reads the status value without adding it to the effect's dependency list.
2
status = 'alert'
Updates state conditionally based on the untracked value to avoid circular updates.