Svelte Core Bestpractices
SvelteOfficialPublished by Svelte
- Skill
- Guidelines
- Software development
- MIT
- No issues found
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
Download the skill as a ZIP:
https://autogineer.com/agent-skills/sveltejs/svelte-core-bestpractices/downloadUnzip 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]
$derivedis 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
$inspectIf 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
$stateinstead of implicit reactivity (e.g.let count = 0; count += 1)use
$derivedand$effectinstead of$:assignments and statements (but only use effects when there is no better solution)use
$propsinstead ofexport let,$$propsand$$restPropsuse
onclick={...}instead ofon:click={...}use
{#snippet ...}and{@render ...}instead of<slot>and$$slotsand<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
$statefields to share reactivity between components, instead of using storesuse
{@attach ...}instead ofuse:actionuse clsx-style arrays and objects in
classattributes, instead of theclass:directive
Files
- ATTRIBUTION.mdAdded by AutoGineer873 B
- LICENSELicence file added by AutoGineer1.1 KiB
- SKILL.md7.5 KiB
- references/attach.md4.8 KiB
- references/await-expressions.md6.4 KiB
- references/bind.md522 B
- references/each.md1.2 KiB
- references/hydratable.md4.1 KiB
- references/inspect.md2.2 KiB
- references/render.md841 B
- references/snippet.md8.2 KiB
- references/svelte-reactivity.md1.8 KiB
references/hydratable.md
In Svelte, when you want to render asynchronous content data on the server, you can simply await it. This is great! However, it comes with a pitfall: when hydrating that content on the client, Svelte has to redo the asynchronous work, which blocks hydration for however long it takes:
<script>
import { getUser } from 'my-database-library';
// This will get the user on the server, render the user's name into the h1,
// and then, during hydration on the client, it will get the user _again_,
// blocking hydration until it's done.
const user = await getUser();
</script>
<h1>{user.name}</h1>That's silly, though. If we've already done the hard work of getting the data on the server, we don't want to get it again during hydration on the client. hydratable is a low-level API built to solve this problem. You probably won't need this very often — it will be used behind the scenes by whatever datafetching library you use. For example, it powers remote functions in SvelteKit.
To fix the example above:
<script>
import { hydratable } from 'svelte';
import { getUser } from 'my-database-library';
// During server rendering, this will serialize and stash the result of `getUser`, associating
// it with the provided key and baking it into the `head` content. During hydration, it will
// look for the serialized version, returning it instead of running `getUser`. After hydration
// is done, if it's called again, it'll simply invoke `getUser`.
const user = await hydratable('user', () => getUser());
</script>
<h1>{user.name}</h1>This API can also be used to provide access to random or time-based values that are stable between server rendering and hydration. For example, to get a random number that doesn't update on hydration:
import { hydratable } from 'svelte';
const rand = hydratable('random', () => Math.random());If you're a library author, be sure to prefix the keys of your hydratable values with the name of your library so that your keys don't conflict with other libraries.
Serialization
All data returned from a hydratable function must be serializable. But this doesn't mean you're limited to JSON — Svelte uses devalue, which can serialize all sorts of things including Map, Set, URL, and BigInt. Check the documentation page for a full list. In addition to these, thanks to some Svelte magic, you can also fearlessly use promises:
<script>
import { hydratable } from 'svelte';
const promises = hydratable('random', () => {
return {
one: Promise.resolve(1),
two: Promise.resolve(2)
}
});
</script>
{await promises.one}
{await promises.two}CSP
hydratable adds an inline <script> block to the head returned from render. If you're using Content Security Policy (CSP), this script will likely fail to run. You can provide a nonce to render:
const nonce = crypto.randomUUID();
const { head, body } = await render(App, {
csp: { nonce }
});This will add the nonce to the script block, on the assumption that you will later add the same nonce to the CSP header of the document that contains it:
response.headers.set(
'Content-Security-Policy',
`script-src 'nonce-${nonce}'`
);It's essential that a nonce — which, British slang definition aside, means 'number used once' — is only used when dynamically server rendering an individual response.
If instead you are generating static HTML ahead of time, you must use hashes instead:
const { head, body, hashes } = await render(App, {
csp: { hash: true }
});hashes.script will be an array of strings like ["sha256-abcd123"]. As with nonce, the hashes should be used in your CSP header:
response.headers.set(
'Content-Security-Policy',
`script-src ${hashes.script.map((hash) => `'${hash}'`).join(' ')}`
);We recommend using nonce over hash if you can, as hash will interfere with streaming SSR in the future.
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