$effect runs a function when state updates — for calling third-party libraries, drawing on canvas elements, or making network requests — and only in the browser, never during server-side rendering. Treat it as an escape hatch for things like analytics and direct DOM manipulation, not a frequently used tool: do not update state inside effects, which makes code convoluted and often leads to never-ending update cycles, and do not use an effect to synchronise state — use $derived or $derived.by instead. Effects run after the component mounts to the DOM, then in a microtask after state changes; re-runs are batched and happen after DOM updates. Returning a function creates a teardown that runs immediately before the effect re-runs and when the component is destroyed. Dependencies are the reactive values ($state, $derived, $props) read synchronously, including via function calls, during the last run; values read after an await or inside setTimeout are not tracked, so conditional reads change what re-triggers the effect. Use $effect.pre when code must run before DOM updates. Scope: Svelte 5. Reviewed October 4, 2026.
$effect usage rules
Document v1 · published by Koskamo editorial · updated 2026-10-04
Source and provenance
- Original source
- svelte.dev
- Published on Koskamo by
- Koskamo editorial
- Citation version
- Document v1
- Reuse
- Original summaries; linked sources retain their own terms.