Generated banner for Svelte Core Bestpractices
Generated logo for Svelte Core Bestpractices

Svelte Core Bestpractices

SvelteOfficialPublished by Svelte

  • Skill
  • Guidelines
  • Software development
  • MIT
  • No issues found

From the author

Guidance on writing fast, robust, modern Svelte code. Load this skill whenever in a Svelte project and asked to write/edit or analyze a Svelte component or module. Covers reactivity, event handling, styling, integration with libraries and more.
— the description by Svelte

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a comprehensive guide to the Svelte 5 paradigm, focusing on the use of runes for reactivity and modern component patterns. It emphasizes writing clean, maintainable code by leveraging features like state, derived, and snippets while avoiding legacy patterns. The guidance covers reactivity management, efficient DOM updates, styling strategies, and handling asynchronous operations within components.

What it does

  • Explains the correct usage of Svelte 5 runes including state, derived, and effect.
  • Provides patterns for efficient component styling and CSS custom property usage.
  • Outlines modern approaches to event handling and component communication.
  • Details how to use snippets for reusable markup structures.
  • Offers guidance on debugging reactivity with inspect and trace tools.
  • Recommends modern alternatives to deprecated legacy Svelte features.

When to use it

  • When building or refactoring components in a Svelte 5 project.
  • When you need to determine the most performant way to handle reactive state.
  • When you are unsure whether to use a rune or a legacy pattern.
  • When debugging complex reactivity issues or unexpected component updates.
  • When implementing reusable UI patterns using snippets.

Advantages

  • Promotes consistent and idiomatic Svelte 5 development practices.
  • Reduces performance overhead by encouraging efficient reactivity patterns.
  • Helps developers transition away from deprecated legacy syntax.
  • Improves code maintainability through clear scoping and modern component architecture.

Usage examples

“How should I handle a derived value in Svelte 5?”
The agent will explain using the $derived rune instead of $effect, providing a code example showing the assignment of a reactive expression.
“What is the modern way to handle events in Svelte 5?”
The agent will demonstrate using the onclick attribute directly on elements and using svelte:window for global event listeners.
“How do I replace the old slot system?”
The agent will show how to define and render reusable markup using the snippet and render tags.
“How can I debug why my component is re-rendering too often?”
The agent will suggest using $inspect.trace to identify the specific dependency triggering the update.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/sveltejs/svelte-core-bestpractices/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip svelte-core-bestpractices.zip -d .agents/skills

Documentation by Svelte

$state

Only use the $state rune for variables that should be reactive — in other words, variables that cause an $effect, $derived or template expression to update. Everything else can be a normal variable.

Objects and arrays ($state({...}) or $state([...])) are made deeply reactive, meaning mutation will trigger updates. This has a trade-off: in exchange for fine-grained reactivity, the objects must be proxied, which has performance overhead. In cases where you're dealing with large objects that are only ever reassigned (rather than mutated), use $state.raw instead. This is often the case with API responses, for example.

$derived

To compute something from state, use $derived rather than $effect:

// do this
let square = $derived(num * num);

// don't do this
let square;

$effect(() => {
	square = num * num;
});

[!NOTE] $derived is given an expression, not a function. If you need to use a function (because the expression is complex, for example) use $derived.by.

Deriveds are writable — you can assign to them, just like $state, except that they will re-evaluate when their expression changes.

If the derived expression is an object or array, it will be returned as-is — it is not made deeply reactive. You can, however, use $state inside $derived.by in the rare cases that you need this.

$effect

Effects are an escape hatch and should mostly be avoided. In particular, avoid updating state inside effects.

  • If you need to sync state to an external library such as D3, it is often neater to use {@attach ...}

  • If you need to run some code in response to user interaction, put the code directly in an event handler or use a function binding as appropriate

  • If you need to log values for debugging purposes, use $inspect

  • If you need to observe something external to Svelte, use createSubscriber

Never wrap the contents of an effect in if (browser) {...} or similar — effects do not run on the server.

$props

Treat props as though they will change. For example, values that depend on props should usually use $derived:

// @errors: 2451
let { type } = $props();

// do this
let color = $derived(type === 'danger' ? 'red' : 'green');

// don't do this — `color` will not update if `type` changes
let color = type === 'danger' ? 'red' : 'green';

$inspect.trace

$inspect.trace is a debugging tool for reactivity. If something is not updating properly or running more than it should you can add $inspect.trace(label) as the first line of an $effect or $derived.by (or any function they call) to trace their dependencies and discover which one triggered an update.

#key block

While the #key block is useful when you want transitions/animations to run when a certain expression changes, it can be very expensive — it unmounts every element/component inside each time, so should be used sparingly. Instead of using #key to cause expressions in a child component's <script> block to re-run, for example, consider wrapping those expressions in $derived.

Events

Any element attribute starting with on is treated as an event listener:

<button onclick={() => {...}}>click me</button>

<!-- attribute shorthand also works -->
<button {onclick}>...</button>

<!-- so do spread attributes -->
<button {...props}>...</button>

If you need to attach listeners to window or document you can use <svelte:window> and <svelte:document>:

<svelte:window onkeydown={...} />
<svelte:document onvisibilitychange={...} />

Avoid using onMount or $effect for this.

Snippets

Snippets are a way to define reusable chunks of markup that can be instantiated with the {@render ...} tag, or passed to components as props. They must be declared within the template.

{#snippet greeting(name)}
	<p>hello {name}!</p>
{/snippet}

{@render greeting('world')}

[!NOTE] Snippets declared at the top level of a component (i.e. not inside elements or blocks) can be referenced inside <script>. A snippet that doesn't reference component state is also available in a <script module>, in which case it can be exported for use by other components.

Each blocks

Prefer to use keyed each blocks — this improves performance by allowing Svelte to surgically insert or remove items rather than updating the DOM belonging to existing items.

[!NOTE] The key must uniquely identify the object. Do not use the index as a key.

Avoid destructuring if you need to mutate the item (with something like bind:value={item.count}, for example).

Using JavaScript variables in CSS

If you have a JS variable that you want to use inside CSS you can set a CSS custom property with the style: directive.

<div style:--columns={columns}>...</div>

You can then reference var(--columns) inside the component's <style>.

Styling child components

The CSS in a component's <style> is scoped to that component. If a parent component needs to control the child's styles, the preferred way is to use CSS custom properties:

<!-- Parent.svelte -->
<Child --color="red" />

<!-- Child.svelte -->
<h1>Hello</h1>

<style>
	h1 {
		color: var(--color);
	}
</style>

If this is impossible (for example, the child component comes from a library) you can use :global to override styles:

<div>
	<Child />
</div>

<style>
	div :global {
		h1 {
			color: red;
		}
	}
</style>

Context

Consider using context instead of declaring state in a shared module. This will scope the state to the part of the app that needs it, and eliminate the possibility of it leaking between users when server-side rendering.

Use createContext rather than setContext and getContext, as it provides type safety.

Async Svelte

If using version 5.36 or higher, you can use await expressions and hydratable to use promises directly inside components. Note that these require the experimental.async option to be enabled in the plugin options in vite.config.js or in the svelte.config.js as they are not yet considered fully stable.

Avoid legacy features

Always use runes mode for new code, and avoid features that have more modern replacements:

  • use $state instead of implicit reactivity (e.g. let count = 0; count += 1)

  • use $derived and $effect instead of $: assignments and statements (but only use effects when there is no better solution)

  • use $props instead of export let, $$props and $$restProps

  • use onclick={...} instead of on:click={...}

  • use {#snippet ...} and {@render ...} instead of <slot> and $$slots and <svelte:fragment>

  • use <DynamicComponent> instead of <svelte:component this={DynamicComponent}>

  • use import Self from './ThisComponent.svelte' and <Self> instead of <svelte:self>

  • use classes with $state fields to share reactivity between components, instead of using stores

  • use {@attach ...} instead of use:action

  • use clsx-style arrays and objects in class attributes, instead of the class: directive

Files

references/await-expressions.md

As of Svelte 5.36, you can use the await keyword inside your components in three places where it was previously unavailable:

  • at the top level of your component's <script>

  • inside $derived(...) declarations

  • inside your markup

This feature is currently experimental, and you must opt in by adding the experimental.async option wherever you configure Svelte, usually svelte.config.js:

/// file: svelte.config.js
export default {
	compilerOptions: {
		experimental: {
			async: true
		}
	}
};

The experimental flag will be removed in Svelte 6.

Synchronized updates

When an await expression depends on a particular piece of state, changes to that state will not be reflected in the UI until the asynchronous work has completed, so that the UI is not left in an inconsistent state. In other words, in an example like this...

<!-- codeblock:start {"title":"Synchronized updates"} -->

<!--- file: App.svelte --->
<script>
	let a = $state(1);
	let b = $state(2);

	async function add(a, b) {
		await new Promise((f) => setTimeout(f, 500)); // artificial delay
		return a + b;
	}
</script>

<input type="number" bind:value={a}>
<input type="number" bind:value={b}>

<p>{a} + {b} = {await add(a, b)}</p>

<!-- codeblock:end -->

...if you increment a, the contents of the <p> will not immediately update to read this —

<p>2 + 2 = 3</p>

— instead, the text will update to 2 + 2 = 4 when add(a, b) resolves.

Updates can overlap — a fast update will be reflected in the UI while an earlier slow update is still ongoing.

Concurrency

Svelte will do as much asynchronous work as it can in parallel. For example if you have two await expressions in your markup...

<p>{await one(x)}</p>
<p>{await two(y)}</p>

...both functions will run at the same time, as they are independent expressions, even though they are visually sequential.

This does not apply to sequential await expressions inside your <script> or inside async functions — these run like any other asynchronous JavaScript. An exception is that independent $derived expressions will update independently, even though they will run sequentially when they are first created:

// `b` will not be created until `a` has resolved,
// but once created they will update independently
// even if `x` and `y` update simultaneously
let a = $derived(await one(x));
let b = $derived(await two(y));

[!NOTE] If you write code like this, expect Svelte to give you an await_waterfall warning

Indicating loading states

To render placeholder UI, you can wrap content in a <svelte:boundary> with a pending snippet. This will be shown when the boundary is first created, but not for subsequent updates, which are globally coordinated.

After the contents of a boundary have resolved for the first time and have replaced the pending snippet, you can detect subsequent async work with $effect.pending(). This is what you would use to display a "we're asynchronously validating your input" spinner next to a form field, for example.

You can also use settled() to get a promise that resolves when the current update is complete:

import { tick, settled } from 'svelte';

async function onclick() {
	updating = true;

	// without this, the change to `updating` will be
	// grouped with the other changes, meaning it
	// won't be reflected in the UI
	await tick();

	color = 'octarine';
	answer = 42;

	await settled();

	// any updates affected by `color` or `answer`
	// have now been applied
	updating = false;
}

Error handling

Errors in await expressions will bubble to the nearest error boundary.

Server-side rendering

Svelte supports asynchronous server-side rendering (SSR) with the render(...) API. To use it, simply await the return value:

/// file: server.js
import { render } from 'svelte/server';
import App from './App.svelte';

const { head, body } = +++await+++ render(App);

[!NOTE] If you're using a framework like SvelteKit, this is done on your behalf.

If a <svelte:boundary> with a pending snippet is encountered during SSR, that snippet will be rendered while the rest of the content is ignored. All await expressions encountered outside boundaries with pending snippets will resolve and render their contents prior to await render(...) returning.

[!NOTE] In the future, we plan to add a streaming implementation that renders the content in the background.

Forking

The fork(...) API, added in 5.42, makes it possible to run await expressions that you expect to happen in the near future. This is mainly intended for frameworks like SvelteKit to implement preloading when (for example) users signal an intent to navigate.

<script>
	import { fork } from 'svelte';
	import Menu from './Menu.svelte';

	let open = $state(false);

	/** @type {import('svelte').Fork | null} */
	let pending = null;

	function preload() {
		pending ??= fork(() => {
			open = true;
		});
	}

	function discard() {
		pending?.discard();
		pending = null;
	}
</script>

<button
	onfocusin={preload}
	onfocusout={discard}
	onpointerenter={preload}
	onpointerleave={discard}
	onclick={() => {
		pending?.commit();
		pending = null;

		// in case `pending` didn't exist
		// (if it did, this is a no-op)
		open = true;
	}}
>open menu</button>

{#if open}
	<!-- any async work inside this component will start
	     as soon as the fork is created -->
	<Menu onclose={() => open = false} />
{/if}

Caveats

As an experimental feature, the details of how await is handled (and related APIs like $effect.pending()) are subject to breaking changes outside of a semver major release, though we intend to keep such changes to a bare minimum.

Breaking changes

Effects run in a slightly different order when the experimental.async option is true. Specifically, block effects like {#if ...} and {#each ...} now run before an $effect.pre or beforeUpdate in the same component, which means that in very rare situations.

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Svelte
Publisher
Svelte (Official)
Source
sveltejs/ai-tools · tools/skills/svelte-core-bestpractices · commit d3e755b
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced
Also distributed in
sveltejs/ai-tools, sveltejs/ai-tools, sveltejs/ai-tools, sveltejs/ai-tools

AutoGineer is not affiliated with or endorsed by Svelte or Svelte.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download svelte-core-bestpractices.zip