Welcome to this lesson on Universal Reactivity and State Inspection in Svelte. By now, you are already familiar with Svelte’s $state
and $derived
runes, which allow you to manage reactivity efficiently within components. In this lesson, we will focus on leveraging these tools to create universal reactivity, enabling shared state across multiple components.
Universal reactivity allows state to be defined and accessed outside of individual components, making it possible to manage application-wide data in a modular and scalable way. Additionally, you will learn how to use the $inspect
rune to track state changes, which is essential for debugging and gaining insights into your application's reactivity flow. By the end of this lesson, you will be able to build applications with shared reactive state while effectively monitoring and debugging state transitions.
Let's start by setting up a reactive cart store using Svelte's $state
and $derived
. This will form the backbone of our application, allowing us to manage the items in a shopping cart and keep track of the total number of items.
In the cartStore.svelte.ts
file, we define two exports: cartItems
and totalItems
. cartItems
is initialized as an empty array using , which makes it reactive. This means any changes to will automatically trigger updates in the UI. is a derived value, calculated using to reflect the length of .
