What is $state in Svelte 5: Simple Explanation and Usage
$state in Svelte 5 is a special reactive store that holds the component's local state and allows automatic updates when the state changes. It simplifies managing and reacting to state changes inside components without manual subscriptions or extra boilerplate.How It Works
Imagine your component's state as a box that holds values you want to keep track of, like a counter or a user's name. In Svelte 5, $state acts like this box but with magic: whenever you change something inside it, Svelte automatically updates the parts of your page that depend on those values.
This works because $state is a reactive store built into the component. When you assign new values to it, Svelte notices the change and refreshes the UI where needed, like a friend who instantly reacts when you tell them something new.
Using $state means you don't have to write extra code to watch for changes or update the display manually. It keeps your code clean and your app responsive.
Example
This example shows a simple counter using $state. Clicking the button increases the count, and the displayed number updates automatically.
<script> $state.count = 0; function increment() { $state.count += 1; } </script> <button on:click={increment}>Increment</button> <p>Count: {$state.count}</p>
When to Use
Use $state when you want to keep track of values that change over time inside a Svelte component, like form inputs, counters, toggles, or any interactive data. It is perfect for local state that doesn't need to be shared globally.
For example, if you build a quiz app, $state can hold the current question number and user answers. When the user clicks next, updating $state will automatically refresh the displayed question.
It helps keep your code simple and reactive without extra libraries or complex setups.
Key Points
$stateis a built-in reactive store for local component state in Svelte 5.- It automatically updates the UI when state changes, reducing boilerplate.
- Ideal for managing simple, local, interactive data inside components.
- Helps write cleaner and more readable reactive code.
Key Takeaways
$state holds local reactive state inside Svelte 5 components.$state automatically refreshes the UI where used.$state for simple interactive data like counters or form inputs.