Managing Form State with `$state` in Svelte
Introduction to Form State Management
In the previous lessons, you learned how to use Svelte’s reactivity system to manage dynamic data, such as timers and URLs, using $effect and reactive built-ins like SvelteDate and SvelteURL. Now, we’ll shift our focus to a common real-world use case: managing form state. Forms are a fundamental part of web applications, and handling their state effectively is crucial for creating smooth user experiences.
In this lesson, you’ll learn how to use the $state rune to manage form data reactively. By the end, you’ll be able to build a form that updates its state in real time and handles submissions gracefully. This builds on the reactivity concepts you’ve already learned, applying them to a practical scenario.
Let’s dive in!
Creating a Reactive Form with `$state`
To manage form state in Svelte, we’ll use the $state rune to create a reactive object that holds the form’s data. This object will automatically update whenever the user interacts with the form, ensuring the UI stays in sync with the input values.
Here’s how to define a reactive state object for a form:
In this example, formData is a reactive object that contains fields for firstName, lastName, email, age, gender, and subscribe. The $state rune ensures that any changes to these fields are automatically reflected in the UI.
Next, we’ll bind the form inputs to this state object using Svelte’s bind:value, bind:group, and bind:checked directives. Here’s how to bind a text input for the firstName field:
Similarly, we can bind radio buttons to the gender field and a checkbox to the subscribe field:
By binding the form inputs to the formData object, any changes the user makes will automatically update the state, and vice versa.
