0
0
SvelteConceptBeginner · 3 min read

What is $derived in Svelte 5: Explained Simply

$derived in Svelte 5 is a special reactive store that automatically updates its value based on other stores. It lets you create values that depend on one or more stores, keeping your UI in sync without manual updates.
⚙️

How It Works

Imagine you have a recipe that depends on several ingredients. If any ingredient changes, the recipe updates automatically. $derived works the same way in Svelte 5. It watches one or more stores (ingredients) and recalculates its value (the recipe) whenever those stores change.

This means you don’t have to manually update values that depend on others. $derived keeps everything in sync like a smart assistant, so your app stays reactive and clean.

💻

Example

This example shows how derived creates a new store that combines two number stores and updates automatically when either changes.

javascript
import { writable, derived } from 'svelte/store';

const a = writable(3);
const b = writable(4);

const sum = derived([a, b], ([$a, $b]) => $a + $b);

// Usage in a Svelte component
// <p>The sum is {$sum}</p>
Output
The sum is 7
🎯

When to Use

Use derived when you want to create a value that depends on other reactive stores. It is perfect for calculated data like totals, filtered lists, or combined states.

For example, in a shopping cart app, you can use derived to calculate the total price from item quantities and prices. This keeps your UI updated automatically without extra code.

Key Points

  • derived creates reactive values based on other stores.
  • It updates automatically when dependencies change.
  • Helps keep your app state simple and reactive.
  • Supports multiple input stores and custom calculation functions.

Key Takeaways

derived creates reactive stores that depend on other stores and update automatically.
It simplifies managing computed or combined state in your Svelte app.
Use it for values like sums, filtered data, or any derived information.
It keeps your UI in sync without manual updates or extra code.