Lesson 3
Reactivity in Svelte
Introduction to Reactivity in Svelte

Welcome back! In the previous lesson, you learned how to create your first Svelte component and manage state using runes, a new feature in Svelte 5. Now, we will delve deeper into Svelte's unique approach to reactivity. Reactivity is a core concept in Svelte that allows your application to respond dynamically to changes in state. Unlike traditional frameworks that use stores, Svelte 5 introduces runes to handle reactivity, making it more intuitive and efficient. In this lesson, we will explore how to use runes to create reactive components that update automatically when the state changes.

Understanding Runes in Svelte

In Svelte, runes are the primary mechanism for managing state and reactivity. You have already been introduced to the $state rune, which allows you to define reactive state variables. This lesson will also introduce the $derived rune, which is used to compute values based on changes in state. The $state rune is straightforward: it creates a reactive variable that updates the UI whenever its value changes. The $derived rune, on the other hand, is used to derive new values from existing state variables, ensuring that your UI remains consistent with the underlying data.

The $derived Rune in Svelte

The $derived rune in Svelte is used to compute values based on other reactive state variables. It automatically updates whenever its dependencies change, making it useful for keeping derived values consistent without manual recalculations. This improves code clarity and efficiency by separating computed logic from state mutations.

Consider the following example where we use $derived to calculate a sum of numbers:

svelte
1<script lang="ts"> 2 let numbers: number[] = $state([1, 2, 3, 4]); 3 let total: number = $derived(numbers.reduce((t, n) => t + n, 0)); 4 5 function addNumber() { 6 numbers.push(numbers.length + 1); 7 } 8</script> 9 10<p>{numbers.join(' + ')} = {total}</p> 11 12<button onclick={addNumber}> 13 Add a number 14</button>
Example: Building a Reactive Component

Let's build a reactive component using the following example code:

svelte
1<script lang="ts"> 2 let numbers: number[] = $state([1, 2, 3, 4]); 3 let total: number = $derived(numbers.reduce((t, n) => t + n, 0)); 4 5 function addNumber() { 6 numbers.push(numbers.length + 1); 7 } 8</script> 9 10<p>{numbers.join(' + ')} = {total}</p> 11 12<button onclick={addNumber}> 13 Add a number 14</button> 15 16<style> 17 h1 { 18 color: blue; 19 } 20 21 button { 22 margin-top: 1em; 23 padding: 0.5em 1em; 24 font-size: 16px; 25 } 26</style>

In this example, we use the $state rune to initialize an array of numbers. The $derived rune is then used to calculate the total sum of these numbers. The addNumber function adds a new number to the array, demonstrating how the component's state can be updated. As the state changes, the UI automatically updates to reflect the new total, showcasing Svelte's reactivity.

Implementing Interactions with Event Handling

Svelte simplifies event handling by using attributes like onclick directly in your HTML. In the example above, the Add a number button uses the onclick attribute to trigger the addNumber function. This function updates the numbers array, which in turn updates the total due to the reactivity provided by the $state and $derived runes. This seamless interaction between state and UI is a hallmark of Svelte's reactivity model.

Styling the Component

Styling in Svelte is straightforward and scoped to the component by default. In the example, we apply styles to the <h1> and <button> elements. The <h1> element is styled with a blue color, while the button is given a margin, padding, and font size to enhance its appearance. These styles ensure that your component not only functions well but also looks appealing.

Summary and Preparation for Practice

In this lesson, you explored Svelte's approach to reactivity using runes. You learned how to manage state with $state, compute derived values with $derived, and handle user interactions with event attributes like onclick. These concepts are crucial for building dynamic and responsive applications in Svelte. As you move forward, I encourage you to experiment with the example code by adding new features or modifying existing ones. The upcoming practice exercises will reinforce these concepts and help you gain confidence in creating reactive components. Happy coding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.