javascript / expert
Snippet
Fine-grained Dependency Isolation with $untrack
In Svelte 5, effects automatically subscribe to any rune accessed within their scope. To prevent an effect from re-running when a specific piece of state changes—while still needing that state's value for the execution—we use the $untrack rune. This is essential for preventing unnecessary executions in performance-critical rendering paths or when coordinating state that shouldn't create a circular dependency.
snippet.js
1
2
3
4
5
6
7
8
9
$effect(() => {console.log('Triggered by:', activeUser.id);$untrack(() => {// Reading theme doesn't subscribe the effect to theme changesapplyStyles(activeUser.id, theme.current);analytics.logEvent('user_view', { theme: theme.current });});});
svelte
Breakdown
1
$effect(() => {
Declares a side effect that tracks reactive dependencies.
2
$untrack(() => {
Wraps a block of code to prevent the surrounding effect from subscribing to the runes inside.
3
theme.current
The value is read here, but because it is inside $untrack, changes to 'theme.current' won't re-trigger the effect.