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
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:

<script lang="ts">
    let numbers: number[] = $state([1, 2, 3, 4]);
    let total: number = $derived(numbers.reduce((t, n) => t + n, 0));

    function addNumber() {
        numbers.push(numbers.length + 1);
    }
</script>

<p>{numbers.join(' + ')} = {total}</p>

<button onclick={addNumber}>
    Add a number
</button>
Example: Building a Reactive Component
Implementing Interactions with Event Handling
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
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal