Only use the
rune for variables that should be
reactive — in other words, variables that cause an
,
or template expression to update. Everything else can be a normal variable.
Objects and arrays (
or
) 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
instead. This is often the case with API responses, for example.
To compute something from state, use
rather than
:
js
// do this
let square = $derived(num * num);
// don't do this
let square;
$effect(() => {
square = num * num;
});
[!NOTE]
is given an expression,
not a function. If you need to use a function (because the expression is complex, for example) use
.
Deriveds are writable — you can assign to them, just like
, 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
inside
in the rare cases that you need this.
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
- 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
- If you need to observe something external to Svelte, use
Never wrap the contents of an effect in
or similar — effects do not run on the server.
Treat props as though they will change. For example, values that depend on props should usually use
:
js
// @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';
is a debugging tool for reactivity. If something is not updating properly or running more than it should you can add
as the first line of an
or
(or any function they call) to trace their dependencies and discover which one triggered an update.
Events
Any element attribute starting with
is treated as an event listener:
svelte
<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
or
you can use
and
:
svelte
<svelte:window onkeydown={...} />
<svelte:document onvisibilitychange={...} />
Snippets
Snippets are a way to define reusable chunks of markup that can be instantiated with the
tag, or passed to components as props. They must be declared within the template.
svelte
{#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
. A snippet that doesn't reference component state is also available in a
, 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
, 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
directive.
svelte
<div style:--columns={columns}>...</div>
You can then reference
inside the component's
.
Styling child components
The CSS in a component's
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:
svelte
<!-- Parent.svelte -->
<Child --color="red" />
<!-- Child.svelte -->
<h1>Hello</h1>
<style>
h1 {
color: var(--color);
}
</style>
If this impossible (for example, the child component comes from a library) you can use
to override styles:
svelte
<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
rather than
and
, 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
option to be enabled in
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 instead of implicit reactivity (e.g.
let count = 0; count += 1
)
- use and instead of assignments and statements (but only use effects when there is no better solution)
- use instead of , and
- use instead of
- use and instead of and and
- use instead of
<svelte:component this={DynamicComponent}>
- use
import Self from './ThisComponent.svelte'
and instead of
- use classes with fields to share reactivity between components, instead of using stores
- use instead of
- use clsx-style arrays and objects in attributes, instead of the directive