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/attach.md
Attachments are functions that run in an effect when an element is mounted to the DOM or when state read inside the function updates.
Optionally, they can return a function that is called before the attachment re-runs, or after the element is later removed from the DOM.
[!NOTE] Attachments are available in Svelte 5.29 and newer.
<!--- file: App.svelte --->
<script>
/** @type {import('svelte/attachments').Attachment} */
function myAttachment(element) {
console.log(element.nodeName); // 'DIV'
return () => {
console.log('cleaning up');
};
}
</script>
<div {@attach myAttachment}>...</div>An element can have any number of attachments.
Attachment factories
A useful pattern is for a function, such as tooltip in this example, to return an attachment (demo:
<!--- file: App.svelte --->
<script>
import tippy from 'tippy.js';
let content = $state('Hello!');
/**
* @param {string} content
* @returns {import('svelte/attachments').Attachment}
*/
function tooltip(content) {
return (element) => {
const tooltip = tippy(element, { content });
return tooltip.destroy;
};
}
</script>
<input bind:value={content} />
<button {@attach tooltip(content)}>
Hover me
</button>Since the tooltip(content) expression runs inside an effect, the attachment will be destroyed and recreated whenever content changes. The same thing would happen for any state read inside the attachment function when it first runs. (If this isn't what you want, see Controlling when attachments re-run.)
Inline attachments
Attachments can also be created inline (demo:
<!--- file: App.svelte --->
<canvas
width={32}
height={32}
{@attach (canvas) => {
const context = canvas.getContext('2d');
$effect(() => {
context.fillStyle = color;
context.fillRect(0, 0, canvas.width, canvas.height);
});
}}
></canvas>[!NOTE] The nested effect runs whenever
colorchanges, while the outer effect (wherecanvas.getContext(...)is called) only runs once, since it doesn't read any reactive state.
Conditional attachments
Falsy values like false or undefined are treated as no attachment, enabling conditional usage:
<div {@attach enabled && myAttachment}>...</div>Passing attachments to components
When used on a component, {@attach ...} will create a prop whose key is a Symbol. If the component then spreads props onto an element, the element will receive those attachments.
This allows you to create wrapper components that augment elements (demo:
<!--- file: Button.svelte --->
<script>
/** @type {import('svelte/elements').HTMLButtonAttributes} */
let { children, ...props } = $props();
</script>
<!-- `props` includes attachments -->
<button {...props}>
{@render children?.()}
</button><!--- file: App.svelte --->
<script>
import tippy from 'tippy.js';
import Button from './Button.svelte';
let content = $state('Hello!');
/**
* @param {string} content
* @returns {import('svelte/attachments').Attachment}
*/
function tooltip(content) {
return (element) => {
const tooltip = tippy(element, { content });
return tooltip.destroy;
};
}
</script>
<input bind:value={content} />
<Button {@attach tooltip(content)}>
Hover me
</Button>Controlling when attachments re-run
Attachments, unlike actions, are fully reactive: {@attach foo(bar)} will re-run on changes to foo or bar (or any state read inside foo):
// @errors: 7006 2304 2552
function foo(bar) {
return (node) => {
veryExpensiveSetupWork(node);
update(node, bar);
};
}In the rare case that this is a problem (for example, if foo does expensive and unavoidable setup work) consider passing the data inside a function and reading it in a child effect:
// @errors: 7006 2304 2552
function foo(+++getBar+++) {
return (node) => {
veryExpensiveSetupWork(node);
+++ $effect(() => {
update(node, getBar());
});+++
}
}Creating attachments programmatically
To add attachments to an object that will be spread onto a component or element, use createAttachmentKey.
Converting actions to attachments
If you're using a library that only provides actions, you can convert them to attachments with fromAction, allowing you to (for example) use them with components.
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