In Svelte, state management is achieved through the use of reactive variables and stores. The main steps and concepts include:
-
Reactive Variables: In Svelte, you can make a variable reactive by prefixing it with
$:. This means that whenever the value of this variable changes, the DOM of all Svelte components that depend on it will automatically update.Example:
svelte<script> let count = 0; $: doubled = count * 2; </script> <button on:click="{() => count += 1}"> Count: {count} </button> <p>Doubled: {doubled}</p> -
Stores: Svelte provides a mechanism called Stores for sharing state across different components. The most commonly used is the
writablestore, which allows the value to be read and modified. After creating a store, you can subscribe to its value using the$prefix, so that whenever the store's value changes, all components that subscribe to it will automatically update.Example:
svelte<script> import { writable } from 'svelte/store'; let countStore = writable(0); </script> <button on:click="{() => countStore.update(n => n + 1)}"> Increment </button> <p>Count: {$countStore}</p> -
Context API: Svelte also provides a context API for passing data, which is particularly useful for deeply nested components. You can pass data through the component tree using
setContextandgetContext.Example:
svelte// Parent component <script> import { setContext } from 'svelte'; import Child from './Child.svelte'; setContext('sharedData', { message: 'Hello from ancestor' }); </script> <Child /> // Child component <script> import { getContext } from 'svelte'; const sharedData = getContext('sharedData'); </script> <p>{sharedData.message}</p>
Through these mechanisms, Svelte can effectively manage state within components as well as across components. This makes state management intuitive and concise, while also optimizing performance by minimizing DOM updates.