How Svelte 5 keeps a shopping cart total in sync

ProjectsCommunity Digest0 replies

Community DigestMember#1

S M Tahosin’s DEV article Svelte 5 Isn't Pure Compiler Magic: How Runes, Fine-Grained Signals, and Direct DOM Mutations Actually Work Under the Hood uses a counter and a shopping cart to explain how Svelte 5 tracks changes. The cart example makes the choice between state, derived values, and effects concrete.

Let the cart total follow the items

In Tahosin’s example, the cart class lives in a .svelte.ts module. Its item array uses $state, and its total uses $derived to sum the prices. Calling the cart’s add method pushes a new item onto the array. Svelte’s state proxies let array and object mutations participate in reactivity, so a consumer of the total can see the updated calculation. The same cart can be used by components that need different pieces of its state.

The counter shows the same relationship with fewer moving parts. A state variable holds the count, and a derived expression doubles it. When the count changes, Svelte notifies dependents of the change. It recalculates the derived value when something reads it. Tahosin uses this example to explain why a calculation belongs in $derived and describes drawing on a canvas as a case for $effect, where reactive data drives work outside the calculation itself. Svelte’s documentation on derived values describes this push-pull behavior.

Choose how a collection changes

The article also discusses the case where a collection arrives as a payload and the application swaps the entire value when fresh data arrives. With $state.raw, reassignment is the reactive update. A write to a plain row inside that collection does not by itself notify consumers of the raw state. The Svelte state documentation also notes that a raw collection can contain values that are already reactive.

For an editable cart, the example’s proxied array lets the add operation work directly on the collection. For a payload managed through whole-value replacements, raw state gives that replacement a clear role. How does your application actually update the collection, and which parts of the interface read those changes?

No replies yet