Svelte & SvelteKit (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)
Preventing Memory Leaks in `$effect()` and Untracking Dependencies with `untrack()`.
senior LevelCode ExampleSignalsMemory ManagementSystem Design
In Simple Words:
- Unintentional Dependency Tracking: If you read a state variable inside an
$effect()simply for logging or analytics, the effect will re-run every time that state changes! untrack(fn): Prevents the effect from registering the signal as a dependency:svelte<script> import { untrack } from 'svelte'; let count = $state(0); let analyticsId = $state('a1'); $effect(() => { // Tracks ONLY count. If analyticsId changes, effect does NOT re-run! console.log(`Count changed to ${count}`); sendMetric(count, untrack(() => analyticsId)); }); </script>