# Svelte best practices from the docs, tested

- Published: 2026-11-29
- Tags: Why Svelte, Svelte
- URL: https://devtrillo.com/writing/why-svelte-9-svelte-best-practices-from-the-docs/

> Part 9 of a series on Svelte in 2026. [Part 8](/writing/why-svelte-8-shared-state-in-svelte-ts-modules/) put state in `.svelte.ts` modules. This part reads the official best-practices page and runs the rules the series hasn't covered yet.

I rendered a list of three people, ada, grace and linus. Each row had a text input and a button that counts its own clicks. I typed "note" into ada's input, clicked her button twice, then removed ada from the array:

```txt
before:  ada [note | clicks 2]   grace [_ | clicks 0]   linus [_ | clicks 0]
after:   grace [note | clicks 2]   linus [_ | clicks 0]
```

Grace now has ada's note and ada's clicks. Nothing threw, and the compiler had nothing to say about the list. Svelte's best-practices page covers this in one sentence, under "Each blocks", and gives performance as the reason.[^best]

That page showed up in the docs in February 2026.[^history] Its frontmatter says `skill: true`, and Svelte ships the same text as `svelte-core-bestpractices`, an agent skill for Claude Code, Codex and others.[^skills] So it's written to be short enough for a model to load before it touches your component, and it reads that way: a rule, a reason, sometimes a code pair marked "do this" and "don't do this". Agents get part 22. This part is for the humans reading the same page.

## Half of it you've read here

If you've followed the series, about half of the page is review. Only use `$state` for values something reacts to (part 3 showed the compiler already turns a never-reassigned `$state(0)` into a plain `0`, so this rule is mostly about telling the next reader what's live). Use `$state.raw` for big objects you only replace. Compute with `$derived`, not `$effect` (parts 4 and 5). Treat props as though they'll change (part 6). Snippets instead of slots (part 7). Context instead of module state when there's a server, and classes instead of stores (part 8).

One line in that half is worth repeating because people still write the code it forbids: "Never wrap the contents of an effect in `if (browser) {...}` or similar — effects do not run on the server."[^best] I rendered a component with an `$effect` on the server. The script body logged `script ran`. The effect logged nothing, and on the client it logged `effect ran, window is object`. The check is dead code.

I agree with all of that half. The rest of the page is the part I hadn't run, so I ran it.

## Key every list, and not by index

The page says to prefer keyed each blocks so Svelte can "surgically insert or remove items rather than updating the DOM belonging to existing items," and adds: "Do not use the index as a key."[^best] The opening lab is what "updating the DOM belonging to existing items" looks like from the outside. Without a key, Svelte matches rows by position. Removing ada makes the array one shorter, so Svelte keeps rows one and two, hands them grace's and linus's props, and destroys row three. The input's text and the click count were never props, so they stay where they were.

Here are the three ways I keyed the same list:

**Which row gets removed?** Key the list with…

| The each block | After removing ada | Why |
| --- | --- | --- |
| {#each items as item} | grace: input "note", clicks 2 · linus: empty, clicks 0 | No key, so Svelte matches rows by position. Row one still exists, it just gets grace's props. The input and the click count were never props, so they stay. The last row is the one destroyed. |
| {#each items as item, i (i)} | grace: input "note", clicks 2 · linus: empty, clicks 0 | Identical to no key. Index 0 is still there after the removal, so Svelte decides it's the same row. |
| {#each items as item (item.id)} | grace: empty, clicks 0 · linus: empty, clicks 0 | Ada's id is gone, so ada's row is destroyed, input and clicks with it. Grace and linus keep their own rows. |

Keying by index gave the exact output of no key at all. Index 0 still exists after the removal, so Svelte concludes row 0 is the same row. That's why the docs tell you not to do it: it looks like a key and does nothing a missing key wouldn't.

So I'd file this rule under correctness, not speed. Any row with its own state (an input you didn't bind, a component with `$state` inside) goes to the wrong item when the list changes anywhere but the end. React is stricter here. Render a list without keys in React 19.3.1 and the dev build prints `Each child in a list should have a unique "key" prop.`; Svelte 5.57.2 compiled my unkeyed list without a warning.

The same section has a second rule: don't destructure the item if you need to mutate it. That one the compiler enforces. `{#each items as { count }}` with `bind:value={count}` fails with `each_item_invalid_assignment`, and the message tells you the fix: "Use the array and index variables instead." Binding to `item.count` works, since `item` is the deep proxy from part 3. Typing 5 into the mug's input took my total from 3 to 7.

**Quiz:** A list is keyed by index: {#each todos as todo, i (i)}. Each row is a component with its own $state for 'expanded'. You expand the first row, then delete the first todo. Which todo is expanded now?

- None. The expanded row was deleted.
- The todo that used to be second
- Svelte throws, because keys must be unique objects

**Answer:** The todo that used to be second — The row component and its $state stay in place; only its props change. Same as no key at all, which is what my lab showed with the note and the click count.

- Not "None. The expanded row was deleted.": That's what an id key would do. With an index key, index 0 survives the deletion, so Svelte keeps the first row and gives it the next todo's props.
- Not "Svelte throws, because keys must be unique objects": Index keys are unique, so nothing throws. They just don't identify the item.

## `#key` remounts everything inside it

This rule landed in October 2026, so it's the newest on the page.[^history] `{#key expr}` destroys and recreates its contents whenever `expr` changes. The docs call it "very expensive" and say not to use it to make a child's `<script>` re-run.[^best] That's the specific misuse: a child computes something once at the top of its script, it goes stale, and someone wraps the child in `{#key}` so it gets rebuilt.

I made a `Greeting` with both versions in one component:

```svelte title="Greeting.svelte"
<script>
  let { name } = $props();
  const plain = "hello " + name;
  const live = $derived("hello " + name);
</script>

<p>plain: {plain} | derived: {live}</p>
```

The compiler warned `state_referenced_locally` on `plain`, the same warning part 6 found. Then I changed `name` from ada to grace to linus:

```txt
without #key  mounts: ada                 plain: hello ada   | derived: hello linus
with #key     mounts: ada, grace, linus   plain: hello linus | derived: hello linus
```

`{#key}` fixed `plain` by mounting the component three times. `$derived` fixed it with no remount at all. Here that's three `<p>` tags; under a `{#key}` around a whole page section it's every child component, every bit of local state, and every DOM node, rebuilt on each change. Keep `{#key}` for when you want the remount, like replaying an intro transition.

## Listeners on `window`

"Avoid using `onMount` or `$effect` for this," the page says about `window` and `document` listeners, and points at `<svelte:window>` instead.[^best] I wrote both: one component with `<svelte:window onkeydown={...} />`, one with `window.addEventListener` in `onMount`. I mounted and unmounted each three times, then pressed one key.

```txt
svelte:window   []
onMount         ["m1", "m2", "m3"]
```

Three components that no longer exist all heard the key. `onMount` can return a cleanup function, and if you remember to return `removeEventListener` this works.[^lifecycle] `<svelte:window>` is the version you can't forget to clean up, and Svelte removes the listener when the component goes away. I'd follow this rule even though `onMount` is fine when written carefully, because "written carefully" is exactly what fails in code review at 6pm.

## Styles across the component boundary

Scoped styles get part 11, so here's only what the two styling rules compile to. `style:--columns={columns}` sets a custom property on that element, and the server rendered it as `style="--columns: 3;"`. Passing `--color="red"` to a child component is the docs' preferred way for a parent to style a child, and it adds an element to your DOM:

```html
<svelte-css-wrapper style="display: contents; --color: red;">
  <h1 class="svelte-4q4it6">Hello</h1>
</svelte-css-wrapper>
```

The docs say so on the custom-properties page.[^custom] `display: contents` keeps the wrapper out of layout, but it's still in the tree, so a parent selector like `.card > h1` no longer reaches the child's `h1`.

When the child comes from a library and has no custom properties, the page shows a `:global` block: `div :global { h1 { color: red; } }`. It compiled to `.grid.svelte-ygrh4y { h1 { color: blue; } }` in my version, which is native CSS nesting with the outer selector scoped and everything inside it global.

## The legacy list

The page ends with ten old features and their replacements. Most are renames you'd do anyway (`onclick` for `on:click`, `<Self>` for `<svelte:self>`). Two of them change behavior, and those are the ones I'd move first.

Arrays and objects in `class` (since 5.16) replace the `class:` directive. `class={["tag", active && "active", { big: columns > 2 }]}` rendered `class="tag active big"`, and you can pass that value as a prop, which a directive can't do.[^changelog]

`{@attach}` (since 5.29) replaces `use:action`, and the difference showed up in one test.[^changelog] I painted an element's text with an action and another with an attachment, both reading a `color` prop, then changed `color` from red to blue. The action's element stayed red. Actions run once and only see a new argument if you write an `update` method; attachments run in an effect and re-run when the state they read changes.[^attach]

The Async Svelte section is the only one with a caveat: `await` in components (5.36+) still needs `experimental.async`, and the page says it isn't "fully stable."[^best] That's later in the series.

## What I'd add

The page lists `$props` under "treat as though they will change", and part 8 found the same bug one step away: `const { total } = cart` in a component copies the number once. I'd widen that rule to any getter. Read reactive values where you use them, in the template or inside a `$derived`, and the compiler can keep them live.

Apart from the destructuring rule, which the compiler enforces, every rule I ran broke the same way. Nothing threw, nothing logged, and the app kept a stale value or a listener that outlived its component. That's why the page reads as a checklist rather than a tutorial: it lists the mistakes Svelte can't catch for you. Read the [best-practices page](https://svelte.dev/docs/svelte/best-practices) itself; it takes about five minutes.[^best] Then the [`{#each}`](https://svelte.dev/docs/svelte/each) page for keyed blocks and the [`{@attach}`](https://svelte.dev/docs/svelte/@attach) page, which has the clearest account of why attachments replaced actions.[^attach]

Next: transitions and animations.

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

[^history]: The page was added in [sveltejs/svelte#17804](https://github.com/sveltejs/svelte/pull/17804) (February 2026); the `#key` note came in [#18851](https://github.com/sveltejs/svelte/pull/18851) (October 2026).

[^skills]: Svelte docs, [Skills](https://svelte.dev/docs/ai/skills). The skills live in [sveltejs/ai-tools](https://github.com/sveltejs/ai-tools).

[^lifecycle]: Svelte docs, [Lifecycle hooks: `onMount`](https://svelte.dev/docs/svelte/lifecycle-hooks#onMount).

[^custom]: Svelte docs, [Custom properties](https://svelte.dev/docs/svelte/custom-properties).

[^changelog]: [Svelte changelog](https://github.com/sveltejs/svelte/blob/main/packages/svelte/CHANGELOG.md): 5.16.0, "allow `class` attribute to be an object or array, using `clsx`" ([#14714](https://github.com/sveltejs/svelte/pull/14714)); 5.29.0, "attachments" ([#15000](https://github.com/sveltejs/svelte/pull/15000)).

[^attach]: Svelte docs, [`{@attach ...}`](https://svelte.dev/docs/svelte/@attach).

- **Part 10 — Built-in transitions and animations**: transition:, in:/out:, custom css transitions and animate:flip, tested in Chromium: why the reduced-motion reset misses them and why a leaving element is still in the DOM
