# Svelte 4 had dependency arrays. You just never saw them.

- Published: 2026-11-27
- Tags: Why Svelte, Svelte
- URL: https://devtrillo.com/writing/why-svelte-4-dependency-arrays/

> Part 4 of a series on Svelte in 2026. [Part 3](/writing/why-svelte-3-what-state-hides/) covered `$state`. This part covers the values you compute from it.

This is the component the runes announcement used to show why Svelte 4's reactivity had to go:[^runes]

```svelte title="Legacy.svelte"
<script>
  export let width;
  export let height;
  const multiplyByHeight = (w) => w * height;
  $: area = multiplyByHeight(width);
</script>

<p>{area}</p>
```

Change `height` and `area` doesn't move. The output below isn't from Svelte 4's compiler. Svelte 5 still compiles this syntax in legacy mode, so I ran it through 5.57.2 and read what came out:

```js title="Legacy.js (compiled, excerpt)"
const area = $.mutable_source();
let width = $.prop($$props, "width", 8);
let height = $.prop($$props, "height", 8);
const multiplyByHeight = (w) => w * height();

$.legacy_pre_effect(
  () => $.deep_read_state(width()),
  () => {
    $.set(area, multiplyByHeight(width()));
  },
);
```

The first argument to `legacy_pre_effect` is a dependency list. The compiler wrote it from the source text of the `$:` line, and that line only mentions `width`. The `height` read happens inside `multiplyByHeight`, where the compiler doesn't look, so `height` isn't on the list.

That's legacy mode, so it shows the mechanism rather than proving what Svelte 4 emitted. The title's claim rests on the announcement, which says it plainly: `$:` dependencies "are determined when Svelte compiles your component."[^runes] A dependency list, fixed at compile time, built from whatever the compiler could see.

If you've written React, you know this bug. It's `useMemo(fn, [width])` with an entry missing. The difference is that in Svelte 4 nobody typed the array, so nobody could review it either.

Here's the same component with runes:

```svelte title="Runes.svelte"
<script>
  let { width, height } = $props();
  const multiplyByHeight = (w) => w * height;
  const area = $derived(multiplyByHeight(width));
</script>

<p>{area}</p>
```

```js title="Runes.js (compiled, excerpt)"
const multiplyByHeight = (w) => w * $$props.height;
const area = $.derived(() => multiplyByHeight($$props.width));
```

There's no list in the output, because it moved to run time: "Anything read synchronously inside the `$derived` expression … is considered a _dependency_."[^derived] The helper reads `height` while the derived runs, so `height` counts. In the lab, changing `height` from 3 to 10 took `area` from 6 to 20.

You still have a dependency list. You just never write it, and it's built from what actually ran, not from what the compiler could see.

## A value that says what it is

Part 3 showed that component code runs once. The docs spell out what that means for computed values: "Without the `$derived` rune, `doubled` would maintain its original value even when `count` changes."[^derived]

```svelte
<script>
  let count = $state(0);
  let doubled = $derived(count * 2);
</script>
```

`doubled` is a declaration of what the value _is_, and Svelte keeps it true. The expression "should be free of side-effects."[^derived] Svelte enforces that one, as the gotchas show.

Keeping it true takes less work than you'd guess.

## What happens when `count` changes

### Nothing, at first

The docs call the model _push-pull_: on a write, everything downstream "is immediately notified of the change (the 'push'), but derived values are not re-evaluated until they are actually read (the 'pull')."[^derived]

I put a counter inside a `$derived.by` to check. After declaring it: 0 evaluations. After three writes to `count` with no reads: still 0. Then I read it three times and got 1 evaluation. A derived is lazy, and once computed it's cached until something it read changes.

### It tracks what it read last time

```js
let pick = $derived(useA ? a : b);
```

While `useA` is true, the expression never reads `b`, so `b` isn't a dependency. In the lab, changing `b` didn't re-evaluate `pick`. After flipping `useA` to false, changing `a` didn't either. The list is rebuilt on every run, so it only holds what the last run touched.

### It stops when the value didn't change

"If the new value of a derived is referentially identical to its previous value, downstream updates will be skipped."[^derived] The docs' example is a button that shows `large`, where `large = $derived(count > 10)`. Ten clicks take `count` from 0 to 10, and `large` is `false` every time, so the button text never updates. In the lab, the code downstream of `large` ran once at mount and then not again until `count` hit 11.

Here are the lazy read and the cutoff on one graph. Pick a click:

**Push, then pull.** Click the button once: what happens to each node for either click.

| Node | Push (on write) | Pull (on read), count 9 → 10 | Pull (on read), count 10 → 11 |
| --- | --- | --- | --- |
| `count` ($state) | written | — | — |
| `large` ($derived(count > 10)) | dirty | recalculated, still false | recalculated, now true |
| `<button>{large}</button>` (on screen) | notified | skipped, large unchanged | updated |
| `doubled` ($derived(count * 2), never read) | nothing: never read, so not tracked yet | not read, so not computed | not read, so not computed |

**Quiz:** let report = $derived.by(() => expensiveSummary(rows)) is only shown inside {#if showReport}, and showReport is false. A user edits rows 50 times. How many times does expensiveSummary run?

- 50, once per edit
- 0
- 1, at the end, batched

**Answer:** 0 — Deriveds are pulled, not pushed. With nothing reading report, it's never recalculated. It runs once, when showReport turns true.

- Not "50, once per edit": Nothing reads report while the {#if} is false, so the edits never make it run.
- Not "1, at the end, batched": Batching is about effects. A derived nobody reads doesn't run at all.

## `$derived.by` for anything with statements

`$derived` takes an expression. When the value needs a loop or a few lines, use `$derived.by` and pass a function. "`$derived(expression)` is equivalent to `$derived.by(() => expression)`."[^derived]

```js
let numbers = $state([1, 2, 3]);
let total = $derived.by(() => {
  let total = 0;
  for (const n of numbers) total += n;
  return total;
});
```

The two are easy to mix up, and the mistake is silent. `$derived(() => count * 2)` gives you the function. In the lab, `typeof oops` was `"function"` and the compiler didn't warn.

## Deriveds you can write to

Since Svelte 5.25, you can assign to a derived.[^changelog] The docs pitch it for optimistic UI: the value follows its source, and you can override it until the source moves.[^derived] This is their example, lightly adapted. I tested the override in the lab, not this component:

```svelte title="Like.svelte"
<script>
  let { post, like } = $props();
  let likes = $derived(post.likes);

  async function onclick() {
    likes += 1;
    try {
      await like();
    } catch {
      likes -= 1;
    }
  }
</script>
```

In the lab, `likes += 1` gave 11 while the source stayed at 10. When the source changed to 20, `likes` went to 20 and the override was gone. Older tutorials will tell you deriveds are read-only. They were: "Prior to Svelte 5.25, deriveds were read-only."[^derived]

If you want the old behaviour, declare it with `const`. `const d = $derived(c * 2); d = 5;` fails to compile with `constant_assignment`.

**Quiz:** let likes = $derived(post.likes). A click runs likes += 1 (optimistic), then the server sends a fresh post with likes: 42. What does the page show?

- The optimistic value plus 42
- 42
- The optimistic value, for good, since you wrote to it

**Answer:** 42 — An override lasts until the derived's dependencies change. The new post re-evaluates it.

- Not "The optimistic value plus 42": Svelte doesn't merge anything. The derived just re-evaluates.
- Not "The optimistic value, for good, since you wrote to it": That's how $state behaves. A derived re-evaluates when its inputs change.

## How React does it

For a cheap value, React's answer has no list at all. "When something can be calculated from the existing props or state, don't put it in state. Instead, calculate it during rendering."[^noeffect] `const total = price * qty;` in the component body is always right, because the whole body runs again on every render.

The list shows up when you want to skip that work. `useMemo` caches "the result of a calculation between re-renders" and compares your dependencies with `Object.is`.[^usememo] Leave one out and you get Svelte 4's bug, typed by hand:

```jsx
const [price, setPrice] = useState(10);
const [qty, setQty] = useState(2);
const total = useMemo(() => price * qty, [price]); // missing qty
```

I rendered it with React 19.3.1:

```
initial:  total 20 | renders 1 memoRuns 1
qty=3:    total 20 | renders 2 memoRuns 1   <- stale, expected 30
price=11: total 33 | renders 3 memoRuns 2
```

The component re-rendered and `useMemo` handed back the cached 20. It caught up only when `price` changed. The `react-hooks/exhaustive-deps` lint flags exactly this; its own invalid example is a `useMemo` missing a dependency.[^deps] React Compiler goes further and writes the memoization for you, with correct dependencies. Part 2 showed its output.

So React re-runs the component and caches by the inputs you declare, or the compiler declares. Svelte doesn't re-run the component, and re-evaluates only the deriveds that read the value that changed.

## Gotchas

**State writes throw.** Writing `$state` inside a derived throws `state_unsafe_mutation`. In dev the message reads: "Updating state inside `$derived(...)`, `$inspect(...)` or a template expression is forbidden."

**Derived objects aren't deep.** "Unlike `$state`, which converts objects and arrays to deeply reactive proxies, `$derived` values are left as-is."[^derived] With `obj = $derived({ value: src })`, setting `obj.value = 99` changed the object, and nothing that read it re-ran. The exception is a derived that points into state: `selected = $derived(items[index])` returns the proxy from part 3, so `selected.name = "A!"` writes through to `items`.

**Destructuring works here.** Part 3 warned that destructuring `$state` copies the values. Destructuring a derived doesn't: `let { first, last } = $derived(...)` is "roughly equivalent" to one derived per property.[^derived] In the lab, mutating the source updated `first`.

**Props need it too.** `let color = type === "danger" ? "red" : "green"` "will not update if `type` changes."[^bp] Wrap it in `$derived`.

**Opting out of a dependency.** `x + untrack(() => y)` re-evaluates when `x` changes and ignores `y`, while still reading its current value.[^derived]

**Finding out why it ran.** Conditional reads mean conditional dependencies, which is what you want until you're debugging. Put `$inspect.trace(label)` on the first line of a `$derived.by` to log which dependency triggered the update.[^bp]

**Don't derive with `$effect`.** "To compute something from state, use `$derived` rather than `$effect`."[^bp] Part 5 covers why.

## The list is still there

All three approaches keep a list of what a value depends on. React makes you write it. Svelte 4 wrote it for you from the source text and missed whatever hid inside a function. Svelte 5 records it while the value is computed, through any helper, and only for the branch that ran. Then it computes as late as it can and stops as soon as nothing changed.

The [`$derived` page](https://svelte.dev/docs/svelte/$derived) covers all of this in a few screens, and most of the quotes here come from it.[^derived] The runes announcement is still the best account of why the compile-time list had to go.[^runes]

Next: `$effect`, and when not to use it.

[^runes]: [Introducing runes](https://svelte.dev/blog/runes) (September 2023).

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

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

[^changelog]: [Svelte changelog](https://github.com/sveltejs/svelte/blob/main/packages/svelte/CHANGELOG.md), 5.25.0: "make deriveds writable" (#15570), published March 2025.

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

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

[^deps]: React docs, [`exhaustive-deps`](https://react.dev/reference/eslint-plugin-react-hooks/lints/exhaustive-deps).

- **Part 5 — Most of your $effects should be something else**: what $effect is for, what goes wrong when you sync state with it, and what to use instead
