CHAPTER 06
Beginner
Variables and State Management
Updated: May 18, 2026
5 min read
# CHAPTER 6
Variables and State Management
1. Chapter Introduction
State is the data your application needs to remember — the current user, a list of items, whether a modal is open. In Svelte, everylet variable inside <script> is potential state. When you assign to it, the UI updates. This chapter covers structuring component state properly, working with complex data types, and knowing when local state is sufficient versus when you need a store.
2. Learning Objectives
- Distinguish between state and derived values.
- Work with primitive, object, and array state.
- Reset and update complex state cleanly.
- Understand the immutable update pattern for arrays.
- Know when to use local state vs global stores.
3. Primitive State
svelte
4. Object State
svelte
5. Array State — The Immutable Pattern
svelte
6. Resetting State
svelte
7. When to Use Local State vs Stores
text
8. Multiple State Variables vs State Object
svelte
9. Common Mistakes
-
Deep object mutations losing reactivity: For deeply nested objects (
user.address.city = 'NY'), adduser = userat the end to force Svelte to notice the change.
-
Sharing state by passing
bind:everywhere: If more than 2-3 components need the same data, use a Svelte store instead of prop drilling.
10. MCQs with Answers
Question 1
In Svelte, what makes a variable "state"?
Question 2
When updating an object property in Svelte, does it trigger reactivity?
Question 3
What is the recommended way to add an item to a reactive array?
Question 4
What technique ensures reactivity when deeply mutating a nested object?
Question 5
What is the immutable update pattern for toggling a property in an array?
Question 6
When should you use a Svelte Store instead of local component state?
Question 7
How do you safely reset state to its initial values?
Question 8
What does $: remaining = todos.filter(t => !t.done).length create?
Question 9
Which approach is better for state that changes together (loading, error, data)?
Question 10
Can you have private (non-reactive) state in a Svelte component?
11. Interview Questions
- Q: Explain the immutable update pattern in Svelte. Why is it necessary for arrays?
- Q: What is the difference between local component state and a Svelte store? Give an example of when you'd use each.
12. Summary
Svelte's state management for components is refreshingly simple:let variables are reactive, object property assignments work, and arrays require the immutable update pattern. For state shared across multiple components, Svelte Stores (Chapter 10) provide an elegant solution. The key skill is knowing which pattern to reach for.
13. Next Chapter Recommendation
State changes in response to user actions. In Chapter 7: Event Handling in Svelte, we learn how to react to clicks, input changes, form submissions, and custom events using Svelte'son: directive.