Svelte best practices from the docs, tested

By Esteban Trillo7 min readWhy SvelteSvelte

No errors, and ada's note is in grace's drawer. The best-practices page is a list of mistakes Svelte can't catch for you.
No errors, and ada's note is in grace's drawer. The best-practices page is a list of mistakes Svelte can't catch for you.

Part 9 of a series on Svelte in 2026. Part 8 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:

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.1

That page showed up in the docs in February 2026.2 Its frontmatter says skill: true, and Svelte ships the same text as svelte-core-bestpractices, an agent skill for Claude Code, Codex and others.3 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.”1 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.”1 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:

Key the list with…
After removing ada
grace: input "note", clicks 2 · linus: empty, clicks 0
Why
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.
After removing ada
grace: input "note", clicks 2 · linus: empty, clicks 0
Why
Identical to no key. Index 0 is still there after the removal, so Svelte decides it's the same row.
After removing ada
grace: empty, clicks 0 · linus: empty, clicks 0
Why
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.

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?

#key remounts everything inside it

This rule landed in October 2026, so it’s the newest on the page.2 {#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.1 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:

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:

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.1 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.

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.4 <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:

<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.5 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.6

{@attach} (since 5.29) replaces use:action, and the difference showed up in one test.6 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.7

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.”1 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 itself; it takes about five minutes.1 Then the {#each} page for keyed blocks and the {@attach} page, which has the clearest account of why attachments replaced actions.7

Next: transitions and animations.

  • 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

Footnotes

  1. Svelte docs, Best practices. ↩ ↩2 ↩3 ↩4 ↩5 ↩6 ↩7

  2. The page was added in sveltejs/svelte#17804 (February 2026); the #key note came in #18851 (October 2026). ↩ ↩2

  3. Svelte docs, Skills. The skills live in sveltejs/ai-tools. ↩

  4. Svelte docs, Lifecycle hooks: onMount. ↩

  5. Svelte docs, Custom properties. ↩

  6. Svelte changelog: 5.16.0, “allow class attribute to be an object or array, using clsx” (#14714); 5.29.0, “attachments” (#15000). ↩ ↩2

  7. Svelte docs, {@attach ...}. ↩ ↩2

Read next

  1. Built-in transitions and animationsNov 29, 2026 Why Svelte · 8 min
  2. Shared state in .svelte.ts modulesNov 29, 2026 Why Svelte · 7 min
  3. Scoped styles: CSS that stays putNov 30, 2026 Why Svelte · 9 min
  4. In Svelte 5, children is a functionNov 28, 2026 Why Svelte · 6 min
  5. SvelteKit fundamentals: routes and layoutsNov 30, 2026 Why Svelte · 8 min
Piwi hands a single letter to the user at a mailbox; a small note reads no noise.

Get the next one in your inbox

One email when a post goes out, with its sketch. Nothing in between, and one link to leave.

Sign in faster next time?

Add a passkey and skip the email link. Your fingerprint, face or device PIN is enough.