Update documentation/docs/97-best-practices/10-best-practices.md

Co-authored-by: ComputerGuy <63362464+Ocean-OS@users.noreply.github.com>
best-practices-doc
Rich Harris 2 weeks ago committed by GitHub
parent 44fd5dc6e2
commit a3e1be7b26
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -8,7 +8,7 @@ This document is meant to collect a series of best practices to write not only c
## `$state` and `$derived`
When writing a Svelte component, each variable that needs to be used inside an effect a derived or in the template must be declared with `$state`. Objects and arrays are automatically deeply reactive, and you can just mutate properties or push to them to trigger reactivity. If you are not mutating or pushing, consider using `$state.raw` to improve performance. Not every variable must be stateful, if a variable is only used to store information and never in an `$effect`, `$derived` or in the template you can avoid using `$state` completely.
When writing a Svelte component, each variable used inside an `$effect`, `$derived` or in the template must be declared with `$state`. Objects and arrays are automatically deeply reactive, and reactivity can be triggered via mutation. If you don't need mutations triggering reactivity, consider using `$state.raw` to improve performance. Not every variable must be stateful; if a variable is never used in an `$effect`, `$derived` or the template you can avoid using `$state` completely.
If one stateful variable depends on another stateful variable, you must use `$derived` to create this new piece of state. `$derived` accepts an expression as input. If you want to use a function, you must use `$derived.by`. Only the stateful variables that are read within a derived actually count as a dependency of that derived. This means that if you guard the read of a stateful variable with an `if`, that stateful variable will only be a dependency when the condition is true. The value of a derived can be overridden; When overridden, the value will change immediately and trigger a DOM update. But when one of the dependencies changes, the value will be recalculated and the DOM updated once again. If a component is receiving a prop and you want a piece of state to be initialised from that prop, usually it's a good idea to use a derived because if that prop is a stateful variable, when it changes, Svelte will just update the value, not remount the component; If the value could be an object, a class, or an array, the suggestion is to use `$state.snapshot` to clone them (`$state.snapshot` is using `structuredClone` under the hood so it might not always be a good idea).

Loading…
Cancel
Save