Svelte Runes Docs
Find Svelte 5 documentation for $state and $derived, then explain usage with a component example.
Svelte · documentation · runes · state · derived
Last updated:
Find the Svelte 5 library documentation for the runes named $state and $derived, then explain the official usage with a small component example.
In [Svelte 5](wiki:Svelte), Runes are a set of compiler-driven instructions used to manage reactivity. They replace older patterns like `let` for state and the `$:` label for derivations. ### 1. `$state` The `$state` rune is used to declare a reactive variable. Unlike previous versions where any top-level `let` was reactive, Svelte 5 requires you to explicitly wrap reactive values in `$state()`. This makes it clear which variables trigger UI updates and allows reactivity to work outside of `.svelte` files (e.g., in `.svelte.js` or `.svelte.ts` files). ### 2. `$derived` The `$derived` rune creates a reactive value that automatically recalculates whenever its dependencies (variables wrapped in `$state`) change. It replaces the `$:` syntax and is more efficient because it only re-runs when necessary and can be used anywhere, not just at the top level of a component. --- ### Component Example: Price Calculator This example demonstrates a basic counter that calculates a total price based on a unit cost and quantity. ### Key Takeaways * **Explicit Reactivity**: You can immediately see what is reactive by looking for the `$` prefix. * **No Side Effects**: Expressions inside `$derived` should be pure (no setting other state variables). * **Standard JS**: Runes look like function calls, making them more compatible with standard JavaScript tools and IDEs. Would you like to see how to handle side effects using the `$effect` rune, or perhaps explore how to use these runes in external JavaScript files? **Next Steps:** - [Learn about the $effect rune](/#settings/apps/web) - [Explore Svelte 5 Snippets](/#settings/apps/web)