Svelte Best Practices
quality 1/10 · low quality
0 net
AI Summary
Official Svelte documentation outlining best practices for writing performant and robust applications, covering runes ($state, $derived, $effect, $props), event handling, snippets, styling patterns, and modern feature usage.
Tags
Entities
Svelte
svelte-core-bestpractices
Best practices • Svelte Docs Skip to main content Tutorial Packages Playground Blog On this page This document outlines some best practices that will help you write fast, robust Svelte apps. It is also available as a svelte-core-bestpractices skill for your agents. $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 = function $derived < number >(expression : number ) : number namespace $derived Declares derived state, i.e. one that depends on other state variables. The expression inside $derived(...) should be free of side-effects. Example: let double = $derived (count * 2 ); @see {@link https://svelte.dev/docs/svelte/$derived Documentation} @param expression The derived state expression $derived ( let num : number num * let num : number num ); // don't do this let square ; function $effect ( fn : () => void | (() => void )) : void namespace $effect Runs code when a component is mounted to the DOM, and then whenever its dependencies change, i.e. $state or $derived values. The timing of the execution is after the DOM has been updated. Example: $effect (() => console .log ( 'The count is now ' + count)); If you return a function from the effect, it will be called right before the effect is run again, or when the component is unmounted. Does not run during server-side rendering. @see {@link https://svelte.dev/docs/svelte/$effect Documentation} @param fn The function to execute $effect (() => { let square : number square = let num : number num * let num : number num ; }); $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 : let { let type : any type } = function $props () : any namespace $props Declares the props that a component accepts. Example: let { optionalProp = 42 , requiredProp , bindableProp = $bindable () } : { optionalProp ?: number ; requiredProps : string ; bindableProp : boolean } = $props (); @see {@link https://svelte.dev/docs/svelte/$props Documentation} $props (); // do this let color = function $derived < "red" | "green" >(expression : "red" | "green" ) : "red" | "green" namespace $derived Declares derived state, i.e. one that depends on other state variables. The expression inside $derived(...) should be free of side-effects. Example: let double = $derived (count * 2 ); @see {@link https://svelte.dev/docs/svelte/$derived Documentation} @param expression The derived state expression $derived ( let type : any type === 'danger' ? 'red' : 'green' ); // don't do this — `color` will not update if `type` changes let color = let type : any 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 > < button { onclick } >... button > < button { ... props } >... button > If you need to attach listeners to window or document you can use and : < 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' )} Snippets declared at the top level of a component (i.e. not inside elements or blocks) can be referenced inside