# Most of your $effects should be something else

- Published: 2026-11-28
- Tags: Why Svelte, Svelte
- URL: https://devtrillo.com/writing/why-svelte-5-effect-escape-hatch/

> Part 5 of a series on Svelte in 2026. [Part 4](/writing/why-svelte-4-dependency-arrays/) covered `$derived`. This part covers the rune you'll be tempted to use instead of it.

This component keeps `doubled` in sync with `count`, and on every click it writes a wrong line to the DOM first:

```svelte title="SyncEffect.svelte"
<script>
  let count = $state(0);
  let doubled = $state(0);

  $effect(() => {
    doubled = count * 2;
  });

  function bump() {
    count++;
    console.log(doubled);
  }
</script>

<button onclick={bump}>{count} * 2 = {doubled}</button>
```

It looks fine and the screen ends up right. I ran it with Svelte 5.57.2 and watched what happened on one click. The handler logged `0`, because the effect hadn't run yet. Then the text node was written twice: first `1 * 2 = 0`, then `1 * 2 = 2`.

The template updated with the new `count` and the old `doubled`. Then the effect ran, wrote `doubled`, and the template updated again. The browser almost certainly never paints the wrong line, since all of this happens in one microtask. The handler did see the stale value, though, and so does any other code that reads `doubled` in that gap.

**One click with a syncing $effect.** Five steps in order. The click sets count to 1. The handler's console.log reads doubled and gets 0, a stale value. The template writes 1 * 2 = 0, also stale. Then the effect runs and sets doubled to 2. Finally the template writes again, 1 * 2 = 2. The stale steps are marked in red.

Swap the effect for `let doubled = $derived(count * 2)` and the handler logs `2`, and the text node is written once.

The docs don't soften this. `$effect` "is best considered something of an escape hatch … rather than a tool you should use frequently. In particular, avoid using it to synchronise state."[^effect] The best-practices page is shorter: "Effects are an escape hatch and should mostly be avoided."[^bp]

So what's it for?

## What an effect is

An effect is a function Svelte re-runs when state it read changes. It runs after the component mounts, and then "in a microtask after state changes." Re-runs are batched, and they "happen after any DOM updates have been applied."[^effect] That last part is why the component above showed a wrong line: the template had already been written by the time the effect fixed `doubled`.

Part 2 showed `template_effect` in compiled output without saying what it was. Here's a component with both kinds:

```svelte title="Greeting.svelte"
<script>
  let name = $state("world");

  $effect(() => {
    document.title = name;
  });
</script>

<h1>hello {name}!</h1>
```

```js title="Greeting.js (compiled, excerpt)"
$.user_effect(() => {
  document.title = $.get(name);
});

$.template_effect(() => $.set_text(text, `hello ${$.get(name) ?? ""}!`));
```

Your template is made of effects. Every `{name}` becomes a small one that updates a single text node. The docs say so: "Svelte uses effects internally to represent logic and expressions in your template."[^effect] `$effect` is the same machinery, handed to you for the things the template can't do, like setting `document.title`.

Compile it for the server and the effect isn't there at all. The output is a string with `name` in it and no trace of `document.title`. Effects only run in the browser.

Dependencies work the way they did for `$derived` in part 4. Whatever the function reads synchronously, "including indirectly, via function calls," is a dependency, and only what it read on the last run counts.[^effect]

## A job for an effect

The docs' example is a timer:

```svelte title="Timer.svelte"
<script>
  let count = $state(0);
  let milliseconds = $state(1000);

  $effect(() => {
    const interval = setInterval(() => {
      count += 1;
    }, milliseconds);

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

<h1>{count}</h1>
<button onclick={() => (milliseconds *= 2)}>slower</button>
```

`setInterval` lives outside Svelte. Nothing in the template can start or stop it, so you need code that runs when `milliseconds` changes. The function you return is the teardown, and it runs "immediately before the effect re-runs" and when the component is destroyed.[^effect] In the lab I logged from both. Mount, one click on "slower", unmount: `setup 1000`, `teardown 1000`, `setup 2000`, `teardown 2000`.

That's the shape of a good effect. State goes in, and something Svelte doesn't control comes out: a canvas, a timer, the document title, an analytics call. No state comes back.

## Where people use it anyway

The best-practices page names the jobs effects end up doing anyway, and a better tool for each.[^bp] Pick one:

**Effect, or something else?** I want to…

| Job | Use | Why |
| --- | --- | --- |
| compute a value from state | `$derived` | It's never stale, and nothing runs until something reads it. |
| do something when the user clicks | `an event handler` | You already know when it happened. Do the work there. |
| keep two inputs in step | `$derived + a function binding` | One value is the source. The other is derived from it, and writing to it writes the source. |
| set up a library on an element | `{@attach}` | It gets the element, re-runs when what it reads changes, and tears down with it. |
| log a value while debugging | `$inspect` | It logs on every change, deep ones included, and does nothing in a production build. |
| read something outside Svelte | `createSubscriber` | It only listens while an effect or the template is reading the value. |
| draw on a canvas, set document.title, start a timer | `$effect` | This is the job: pushing state out to something Svelte doesn't control. |

The one that takes longest to unlearn is two-way sync. The docs use two sliders, money spent and money left, each moved by the other:[^effect]

```svelte
<script>
  const total = 100;
  let spent = $state(0);
  let left = $state(total);

  $effect(() => {
    left = total - spent;
  });

  $effect(() => {
    spent = total - left;
  });
</script>
```

I expected this to loop, and it doesn't. In the lab, setting `spent` to 30 gave `left` 70, and setting `left` to 10 gave `spent` 90. Each write ran both effects once. The second effect wrote a value equal to the one already there, and the update stopped.

It works, and it's still the wrong code. Two pieces of state hold the same fact. Every change runs both effects, and the reader has to work out which one is the source. The fix makes `spent` the source and `left` a derived, and lets the second slider write through a function binding (Svelte 5.9+):[^bind]

```svelte
<script>
  const total = 100;
  let spent = $state(0);
  let left = $derived(total - spent);

  function updateLeft(value) {
    spent = total - value;
  }
</script>

<input type="range" bind:value={spent} max={total} />
<input type="range" bind:value={() => left, updateLeft} max={total} />
```

Same behaviour in the lab: moving `left` to 10 put `spent` at 90, and moving `spent` to 45 put `left` at 55. There's one piece of state and no effects.

**Quiz:** A settings panel should save to localStorage every time settings changes. What do you use?

- $derived
- $effect
- $inspect

**Answer:** $effect — localStorage is outside Svelte, and nothing is computed back into state. That's what an effect is for.

- Not "$derived": A derived computes a value. Writing to localStorage is a side effect, and the docs say deriveds should be free of them.
- Not "$inspect": $inspect is for debugging, and it does nothing in a production build.

**Quiz:** A list should show only the items matching a search box. The current code filters inside an $effect and writes to a $state called visible. What's the fix?

- Wrap the write in untrack
- Use $effect.pre so it runs before the DOM updates
- let visible = $derived(items.filter(...))

**Answer:** let visible = $derived(items.filter(...)) — visible is computed from items and the query, so it's a derived. It's never stale, and it only re-filters when something reads it.

- Not "Wrap the write in untrack": That stops a loop if there is one. visible is still a second copy of a fact, and it's still stale until the effect runs.
- Not "Use $effect.pre so it runs before the DOM updates": That changes when the copy is made. It's still a copy.

## How React does it

React's docs give the same advice in almost the same words. They call effects an escape hatch and say "if there is no external system involved … you shouldn't need an Effect."[^noeffect] They name the failure as well: syncing state in an effect "does an entire render pass with a stale value."

I ported the first component to React 19.3.1, with `useEffect(() => setDoubled(count * 2), [count])`. One click rendered `1 * 2 = 0`, then `1 * 2 = 2`. Computing `const doubled = count * 2` in the body rendered once. Same bug, same fix.

The differences are in how the effects you do need behave.

**You write the dependency list.** `useEffect` takes an array, the lint checks it, and with no array the effect "will re-run after every commit."[^useeffect] A Svelte effect has no array. It re-runs when something it read changes, and an effect that reads no state runs once.

**Strict Mode runs it twice.** In development, React runs "one extra development-only setup+cleanup cycle before the first real setup," to check that your cleanup undoes your setup.[^useeffect] In the lab, the React timer logged `setup 1000`, `teardown 1000`, `setup 1000` on mount. Svelte's dev build logged one `setup 1000`.

**Timing.** React may let the browser paint before running an effect that a click didn't cause.[^useeffect] Svelte runs effects in a microtask, after its DOM updates and before the browser gets to paint. For "I need the DOM before the user sees it," React has `useLayoutEffect`. Svelte has `$effect.pre`, which runs before the DOM updates instead.

**Reading without depending.** React 19.2 added `useEffectEvent` for reading a value inside an effect without reacting to it.[^r192] Svelte's version is the `untrack` function from part 4.

## Gotchas

**Reading and writing the same state loops.** `$effect(() => { count += 1; })` reads `count` and writes it. Svelte stops it and throws `effect_update_depth_exceeded`. The dev message says what to look for: "This typically indicates that an effect reads and writes the same piece of state."

**Async reads aren't tracked.** Anything read after an `await` or inside a `setTimeout` isn't a dependency.[^effect] In the lab, an effect that read `color` directly and `size` inside a `setTimeout` didn't re-run when `size` changed, and did when `color` changed.

**Reading an object isn't reading its fields.** "An effect only reruns when the object it reads changes, not when a property inside it changes."[^effect] Two effects, one reading `obj` and one reading `obj.value`. After two increments of `obj.value`, the first had run once and the second three times.

**Effects belong to components.** Calling `$effect` from an event handler throws `effect_orphan`. It has to run while the component is being set up, or inside another effect. If you really need one outside a component, `$effect.root` creates a scope you clean up yourself.[^effect]

**Don't guard against the server.** "Never wrap the contents of an effect in `if (browser) {...}` or similar — effects do not run on the server."[^bp] The server build doesn't contain them.

**`$effect.pre` sees the old DOM.** In the lab, on a click from 0 to 1, `$effect.pre` saw `count` as 1 and the paragraph still saying `0`. `$effect` saw `1` in both. That's the point of `.pre`: measuring before Svelte changes things, like keeping a chat scrolled to the bottom.[^effect]

**Debugging a re-run.** If an effect runs more than you expect, put `$inspect.trace()` on its first line, as with `$derived.by` in part 4.[^bp]

## The rune you reach for last

`$effect` is the most familiar rune if you've written React, and the one you need least. The template is already made of effects, and `$derived` covers values computed from state. Event handlers, attachments and function bindings cover most of the rest. What's left is the edge where state leaves Svelte. Write effects for that, and when you find yourself writing state from inside one, look for the derived.

The [`$effect` page](https://svelte.dev/docs/svelte/$effect) is worth reading in full; its last section, "When not to use `$effect`," is most of this post's argument.[^effect] React's [You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect) makes the same case at length, with examples that translate to Svelte almost line for line.[^noeffect]

Next: `$props` and `$bindable`.

[^effect]: Svelte docs, [`$effect`](https://svelte.dev/docs/svelte/$effect).

[^bp]: Svelte docs, [Best practices](https://svelte.dev/docs/svelte/best-practices).

[^bind]: Svelte docs, [`bind:`, function bindings](https://svelte.dev/docs/svelte/bind#Function-bindings). Added in 5.9.0.

[^noeffect]: React docs, [You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect).

[^useeffect]: React docs, [`useEffect`](https://react.dev/reference/react/useEffect).

[^r192]: [React 19.2](https://react.dev/blog/2025/10/01/react-19-2) (October 2025).

- **Part 6 — A Svelte prop is a getter, not an argument**: what $props hands a component, why writing to a prop is a local override, and when $bindable is the right door back up
