Skip to main content
Svelte Fundamentals
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, every let 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
1234567
<script>
  // Primitive state — simple and reactive
  let count = 0;
  let username = &#039;Alice';
  let isLoggedIn = false;
  let rating = 4.5;
</script>

4. Object State

svelte
1234567891011121314151617181920
<script>
  let user = {
    name: &#039;Alice',
    email: &#039;alice@example.com',
    age: 28,
    preferences: { theme: &#039;dark', language: 'en' }
  };

  function updateEmail(newEmail) {
    user.email = newEmail; // Property assignment — triggers reactivity!
  }

  function updateTheme(theme) {
    user.preferences.theme = theme; // Nested property — also works!
    user = user; // Sometimes needed to force reactivity on deep nesting
  }
</script>

<p>{user.name} — {user.email}</p>
<p>Theme: {user.preferences.theme}</p>

5. Array State — The Immutable Pattern

svelte
123456789101112131415161718192021222324252627282930313233
<script>
  let todos = [
    { id: 1, text: &#039;Learn Svelte', done: false },
    { id: 2, text: &#039;Build a project', done: false }
  ];

  let nextId = 3;

  function addTodo(text) {
    todos = [...todos, { id: nextId++, text, done: false }]; // New array!
  }

  function toggleTodo(id) {
    todos = todos.map(t => t.id === id ? { ...t, done: !t.done } : t);
  }

  function deleteTodo(id) {
    todos = todos.filter(t => t.id !== id);
  }

  $: remaining = todos.filter(t => !t.done).length;
  $: totalCount = todos.length;
</script>

<p>{remaining} of {totalCount} tasks remaining</p>

{#each todos as todo (todo.id)}
  <div class:done={todo.done}>
    <input type="checkbox" checked={todo.done} on:change={() => toggleTodo(todo.id)} />
    <span>{todo.text}</span>
    <button on:click={() => deleteTodo(todo.id)}>✕</button>
  </div>
{/each}

6. Resetting State

svelte
12345678910111213141516171819202122
<script>
  const INITIAL_STATE = {
    score: 0,
    lives: 3,
    level: 1,
    playerName: &#039;'
  };

  let game = { ...INITIAL_STATE }; // Copy initial state

  function resetGame() {
    game = { ...INITIAL_STATE }; // Reset by spreading initial state
  }

  function levelUp() {
    game = { ...game, level: game.level + 1, score: game.score + 100 };
  }
</script>

<p>Level {game.level} | Score: {game.score} | Lives: {game.lives}</p>
<button on:click={levelUp}>Level Up!</button>
<button on:click={resetGame}>Reset Game</button>

7. When to Use Local State vs Stores

text
1234567891011
Use LOCAL STATE when:
  ✅ The data is only used in one component
  ✅ The data doesn&#039;t need to persist across routes
  ✅ UI-only state (isOpen, activeTab, hovering)

Use SVELTE STORES when:
  ✅ Multiple components need the same data
  ✅ Data persists across component creation/destruction
  ✅ Authentication state
  ✅ Shopping cart data
  ✅ Theme/user preferences

8. Multiple State Variables vs State Object

svelte
12345678910111213141516171819202122
<script>
  // Option 1: Multiple variables (good for simple, independent state)
  let isLoading = false;
  let error = null;
  let data = [];

  // Option 2: State object (good when state changes together)
  let fetchState = { loading: false, error: null, data: [] };

  async function fetchData() {
    // Multiple variables
    isLoading = true;
    error = null;
    try {
      data = await getData();
    } catch (e) {
      error = e.message;
    } finally {
      isLoading = false;
    }
  }
</script>

9. Common Mistakes

  • Deep object mutations losing reactivity: For deeply nested objects (user.address.city = 'NY'), add user = user at 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's on: directive.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·