Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 35 ยท Reactivity with Runes

Side Effects with $effect

Use the $effect rune in Svelte 5 for side effects like logging, timers and DOM work, with cleanup functions, $effect.pre and when not to use effects.

Some work does not produce a value to show; it does something in the outside world: write to document.title, start a timer, draw on a canvas, send an analytics event. Svelte 5 calls these side effects, and the $effect rune runs them when the state they depend on changes.

A first effect

SVELTE
<script>
  let count = $state(0);

  $effect(() => {
    document.title = `Clicked ${count} times`;
  });
</script>

<button onclick={() => count++}>Click</button>

The function runs after the component is added to the page (after mount), and again after the DOM has updated whenever count changes. Svelte learns the dependencies by watching which state is read synchronously while the function runs.

Effects only run in the browser. They do not run during server-side rendering, so you can touch window and document inside them safely.

Cleanup

An effect may return a function. Svelte calls it before the effect reruns and when the component is destroyed. Use it to undo whatever the effect started:

SVELTE
<script>
  let delay = $state(1000);
  let ticks = $state(0);

  $effect(() => {
    const id = setInterval(() => {
      ticks += 1;
    }, delay);

    return () => clearInterval(id);
  });
</script>

<input type="range" min="100" max="2000" bind:value={delay} />
<p>{ticks} ticks every {delay} ms</p>

When delay changes, the old timer is cleared and a new one starts. Without the cleanup you would pile up timers.

Effect life cycle

Mount Effect runs once
Dependency changes Cleanup, then rerun
Destroy Final cleanup
1 / 2

What gets tracked

  • State read synchronously inside the effect is a dependency.
  • State read after an await, inside a setTimeout callback or in an event handler defined in the effect is not.
  • Objects: only the properties you actually read are tracked. Reading user.name does not rerun the effect when user.email changes.

If you must read a value without depending on it, use untrack:

SVELTE
<script>
  import { untrack } from 'svelte';

  let query = $state('');
  let log = $state([]);

  $effect(() => {
    const q = query; // dependency
    untrack(() => log.push(q)); // read/write without depending on log
  });
</script>

Without untrack, pushing to an array that the same effect reads could create an endless loop; Svelte stops those with an error.

$effect.pre and $effect.root

  • $effect.pre(fn) runs before the DOM updates, which is useful for measuring layout before a change (for example, remembering a scroll position).
  • $effect.root(fn) creates an effect scope that is not tied to a component, returning a cleanup function. You need it only in advanced cases like long-lived stores.
  • $effect.tracking() tells you whether you are inside a tracking context.

When not to use an effect

Effects are an escape hatch. Reach for something else first:

You want to... Use
Compute a value from state $derived
React to a user action an event handler
Sync two inputs bind: or one source of truth
Fetch data when a page loads a SvelteKit load function

Setting state inside an effect that depends on that same state is a common bug source. If you find yourself writing it, ask whether $derived or an event handler fits better.

Working with the DOM: bind:this

To use an element in an effect, bind it to a variable. The variable is undefined until the element exists, and effects run after mount, so it is ready by then:

SVELTE
<script>
  let canvas = $state();

  $effect(() => {
    const ctx = canvas.getContext('2d');
    ctx.fillStyle = 'tomato';
    ctx.fillRect(10, 10, 80, 40);
  });
</script>

<canvas bind:this={canvas} width="120" height="80"></canvas>

Stand-in: effects with cleanup

This plain-JS effect runner supports dependencies, a cleanup function that runs before each rerun, and manual disposal, mirroring the life cycle above.

JS Effect with cleanup (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The log shows start, stop, start, stop, start, then a final stop from disposal.

Title sync and a live clock (stand-in page)

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does an $effect first run?

    Effects run after mount and never during server-side rendering.
  2. 2. What is the returned function from an effect for?

    Return a function to undo timers, listeners or subscriptions.
  3. 3. Which read is NOT tracked as a dependency?

    Only synchronous reads during the effect run are tracked.
  4. 4. What is the best tool for a value computed from other state?

    $derived is designed for computed values.

Summary

  • $effect runs side effects after mount and after relevant state changes.
  • Return a cleanup function to undo timers, listeners and subscriptions.
  • Only synchronous reads are dependencies; untrack reads without depending.
  • $effect.pre runs before DOM updates; $effect.root creates a standalone scope.
  • Prefer $derived and event handlers over effects where they fit.

Next: Deep Reactivity and Snapshots