Universal Reactivity and State Inspection in Svelte
Introduction to Universal Reactivity in Svelte
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.
Creating a Reactive Cart Store
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 $state, which makes it reactive. This means any changes to cartItems will automatically trigger updates in the UI. totalItems is a derived value, calculated using $derived to reflect the length of cartItems.
With this setup, cartItems will hold the list of items in the cart, and totalItems will always show the current number of items. Since Svelte does not allow direct export of $derived values, we use the getTotalItems function to retrieve totalItems, ensuring it stays reactive and up-to-date. This reactive store will be used by other components to display and update the cart's contents.
Using Getters and Setters for State Management
For mutable exported states like discount, where we expect a new value to be passed, we need to use getter and setter functions. This ensures controlled updates and prevents unintended modifications.
By using setters for state values like discount, we ensure that state updates are properly managed, keeping reactivity intact while maintaining control over modifications.
Usage in a component:
