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

TypeScript
let discount = $state(0); // New state for discount

export const setDiscount = (val: number) => {
  discount = val;
};

export const getDiscount = () => discount;

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:

Svelte
<script lang="ts">
  import { setDiscount, getDiscount } from '$lib/cartStore.svelte.ts';

  function applyDiscount() {
    setDiscount(10);
  }
</script>

<p>Current Discount: {getDiscount()}</p>
<button onclick={applyDiscount}>
  Apply $10 Discount
</button>
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