svelte-core-bestpractices
sveltejs/ai-tools
Best practices for writing fast, robust Svelte code with modern runes and patterns.
What is svelte-core-bestpractices?
Guidance on Svelte 5 rune-based development covering reactivity, state management, event handling, styling, and component patterns. Load this skill when writing or analyzing Svelte components to ensure code follows current best practices and avoids legacy patterns.
- Use $state, $derived, and $effect runes correctly for fine-grained reactivity
- Manage props with $props and derive computed values to handle prop changes
- Handle events with onclick handlers and svelte:window/svelte:document for global listeners
- Style components with CSS custom properties for parent-child communication and scoped styling
- Use snippets for reusable markup and keyed each blocks for performant list rendering
- Leverage context for state scoping and avoid legacy features like $:, export let, and on: directives
How to install svelte-core-bestpractices
npx skills add https://github.com/sveltejs/ai-tools --skill svelte-core-bestpracticesHow to use svelte-core-bestpractices
- 1.Load the skill when working on a Svelte project or component
- 2.Reference the guidance on $state, $derived, and $effect when implementing reactive logic
- 3.Use $props for component inputs and $derived for computed values that depend on props
- 4.Apply event handling patterns with onclick and svelte:window/svelte:document as needed
- 5.Use CSS custom properties for styling child components and snippets for reusable markup
- 6.Check the legacy features section to avoid outdated patterns in new code
Use cases
- Refactoring a component to use $derived instead of $effect for computed values
- Optimizing large object handling with $state.raw for API responses
- Styling child components via CSS custom properties instead of :global overrides
- Debugging reactivity issues with $inspect.trace to identify unexpected updates
- Converting legacy Svelte code to runes mode and modern patterns
- Svelte developers building new components or refactoring existing code
- Teams migrating to Svelte 5 runes mode from legacy syntax
- Developers optimizing component performance and reactivity patterns
svelte-core-bestpractices FAQ
Use $state for objects and arrays that are mutated, as it provides deep reactivity. Use $state.raw for large objects that are only reassigned (like API responses) to avoid proxy overhead.
No. Use $derived instead of $effect for computing values from state. Effects are an escape hatch and should be avoided when a derived value would work.
Treat props as though they will change. Use $derived to compute values that depend on props, so they update automatically when the prop changes.
Use CSS custom properties (--color) passed to the child component. Only use :global as a fallback when the child component is from a library and cannot accept custom properties.
Use classes with $state fields instead of stores. This provides better type safety and scopes state appropriately without the risk of leaking between users during server-side rendering.
Full instructions (SKILL.md)
Source of truth, from sveltejs/ai-tools.
name: svelte-core-bestpractices description: 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.
$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
$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.
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 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$$restProps - use
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 stores - use
{@attach ...}instead ofuse:action - use clsx-style arrays and objects in
classattributes, instead of theclass:directive
Related skills
More from sveltejs/ai-tools and the wider catalog.

svelte-code-writer
CLI tools for Svelte 5 documentation lookup and code analysis.

ux-designer
Applies modern UX/UI best practices to interface design and review. Use for UI design and critique; accessibility audits (WCAG, EAA); microcopy; forms, navigation, and onboarding; internationalization and RTL; voice, multimodal, and AI interfaces; design systems; and frontend code review.

pdf-converter
Convert PDFs, images, and Office docs to Markdown, Word, HTML, or LaTeX with OCR and 80+ language support.

tanstack-ai
Provider-agnostic, type-safe AI SDK for streaming, tool calling, structured output, and multimodal content.

tanstack-cli
Interactive scaffolding CLI for TanStack Start projects with 30+ integrations and MCP server support.

tanstack-config
Opinionated toolkit for building, versioning, and publishing high-quality JavaScript/TypeScript packages with Vite, ESLint, and semantic versioning.