Svelte 12 ๐งก Deriving Computed Values with $derived() Rune
In any reactive system, managing state that depends on other state is a frequent challenge. Legacy Svelte used the $: syntax to track reactive declarations, but this often left developers guessing how the compiler would behave. The $derived() rune replaces this with an explicit, performance-oriented mechanism for computed values. It allows you to define a variable whose value is automatically recalculated whenever its dependencies change. Because Svelte tracks these dependencies at the runtime level via proxies, $derived() is not just a reactive shortcut; it is a highly optimized, memoized computation engine.
This chapter explores how $derived() works, why it provides superior performance through lazy evaluation, and how it transforms your component logic from imperative, side-effect-heavy code into a clean, declarative graph of data.
Key point: $derived() creates a computed value that automatically tracks its dependencies, recalculating only when those specific reactive inputs change, providing built-in memoization and ensuring the UI remains perfectly in sync with the underlying state.
Why exists
The ambiguity of $: declarations. The legacy $: syntax was a compiler-level hack. $derived() is a runtime primitive, providing predictable behavior and clear error messages when circular dependencies or invalid operations occur.
The performance trade-off. By using lazy evaluation, $derived() ensures that expensive computations only run when the output is actually needed, saving CPU cycles during rapid-fire state updates.
The separation of concerns. $derived() clearly signals that a value is read-only and derived from state, preventing the confusion between writable “source” state and calculated “view” state.
The dependency graph accuracy. Because $derived() integrates with the same proxy system as $state(), it builds an exact dependency graph, preventing unnecessary re-renders in the DOM tree.
The complexity of state transformations. In large applications, derived state often spans multiple components or modules. $derived() allows you to define these transformations in plain JavaScript/TypeScript files, away from the clutter of markup.
a. Simple Derivations
The most basic use case for $derived() is creating a value that depends on one or more $state() variables. The moment any dependency changes, the derived value is marked as “dirty” and will recompute the next time it is accessed.
let price = $state(10);
let qty = $state(2);
// Computed automatically
let total = $derived(price * qty);
You do not need to manually notify Svelte of changes. The $derived() rune detects the reactive proxy usage within its callback, creates a subscription, and ensures total is always up to date.
b. Memoization and Lazy Evaluation
$derived() uses a “pull” rather than a “push” model. It does not recompute the result the second the state changes; instead, it waits until the derived value is actually read (e.g., during a render cycle). If you change state five times but the UI doesn’t need to show the derived value, the computation is never performed.
let items = $state([1, 2, 3]);
// This computation is lazy; it only runs if the DOM reads 'count'
let count = $derived(items.length);
This memoization mechanism is crucial for heavy computations like array filtering or complex string formatting. It prevents expensive operations from clogging the main thread, especially during large-scale state transitions.
c. Block-based Derivation
For complex transformations, you can pass a block (a callback) to $derived(). This allows you to perform multi-step calculations, early returns, or handle complex logic that doesn’t fit into a single-line expression.
let user = $state({ firstName: "Alice", lastName: "Smith" });
let fullName = $derived(() => {
if (!user.firstName) return user.lastName;
return `${user.firstName} ${user.lastName}`;
});
This ensures that the final result of the block is treated as the derived value. It keeps your template logic clean by encapsulating complex formatting rules directly within the derived definition.
Complete Example Session
// ============================================
// PART 1: SIMPLE MATH
// ============================================
let count = $state(1);
let double = $derived(count * 2);
// ============================================
// PART 2: ARRAY TRANSFORMATION
// ============================================
let numbers = $state([1, 2, 3]);
let sum = $derived(numbers.reduce((a, b) => a + b, 0));
// ============================================
// PART 3: STRING FORMATTING
// ============================================
let name = $state("svelte");
let greeting = $derived(`Hello, ${name.toUpperCase()}`);
// ============================================
// PART 4: CONDITIONAL DERIVATION
// ============================================
let score = $state(85);
let grade = $derived(score > 90 ? "A" : "B");
// ============================================
// PART 5: ACCESSING NESTED STATE
// ============================================
let user = $state({ profile: { points: 10 } });
let points = $derived(user.profile.points);
// ============================================
// PART 6: CHAINED DERIVATION
// ============================================
let base = $state(10);
let tax = $derived(base * 0.1);
let total = $derived(base + tax);
// ============================================
// PART 7: FILTERED ARRAYS
// ============================================
let tasks = $state([{ done: true }, { done: false }]);
let pending = $derived(tasks.filter(t => !t.done));
// ============================================
// PART 8: DERIVED OBJECTS
// ============================================
let x = $state(0);
let pos = $derived({ x: x, y: 0 });
// ============================================
// PART 9: EXTERNAL STATE DERIVATION
// ============================================
// import { shared } from './state.js'
let derivedExternal = $derived(shared.val * 2);
// ============================================
// PART 10: COMPLEX BLOCK LOGIC
// ============================================
let raw = $state(5);
let result = $derived(() => {
let val = raw * 10;
return val > 50 ? "High" : "Low";
});
These parts show how $derived() creates a predictable flow of data from raw state to computed UI values.
Quick Reference
Derivation Forms
| Form | Usage |
|---|---|
$derived(expression) | Single line computation |
$derived(() => { ... }) | Multi-line/Block computation |
Properties
| Characteristic | Behavior |
|---|---|
| Lazy | Computed on read |
| Memoized | Cached between reads |
| Read-only | Cannot be assigned to |
| Reactive | Updates when dependencies change |
Best Practices
โ Do This:
let total = $derived(a + b); // โ
Simple math
let summary = $derived(() => { return complexLogic(x); }); // โ
Block logic
let activeUsers = $derived(users.filter(u => u.online)); // โ
Filtering
const price = $derived(base * multiplier); // โ
Clean definitions
โ Don’t Do This:
let x = $derived(0); x = 5; // โ Cannot reassign
let y = $derived(x + 1); $: z = y * 2; // โ Use $derived for z
$derived(count++); // โ No side effects!
let data = $derived(() => { return fetch('/api'); }); // โ Side effects not allowed
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Infinite Loop | Updating state inside derivation | Use $derived only for values |
| Side Effects | Performing API calls inside | Move to $effect |
| Complexity | Overloading single derivation | Split into multiple $derived |
| Async Logic | Awaiting promises in $derived | Use $effect + $state |
Real-World Examples
1. Filtered Todo List
let todos = $state([...]);
let done = $derived(todos.filter(t => t.done));
2. Cart Total Calculation
let items = $state([...]);
let total = $derived(items.reduce((acc, i) => acc + i.price, 0));
3. String Concatenation
let first = $state("John");
let last = $state("Doe");
let full = $derived(`${first} ${last}`);
4. Access Control
let role = $state("admin");
let isAdmin = $derived(role === "admin");
5. Search Filtering
let query = $state("");
let results = $derived(items.filter(i => i.name.includes(query)));
6. Dynamic Scaling
let scale = $state(1);
let width = $derived(originalWidth * scale);
7. Error Aggregation
let errors = $state([]);
let hasError = $derived(errors.length > 0);
8. Date Formatting
let timestamp = $state(Date.now());
let dateString = $derived(new Date(timestamp).toLocaleDateString());
9. Boolean Toggles
let count = $state(0);
let isVisible = $derived(count > 0);
10. Multi-part Validation
let valid = $derived(email.includes('@') && password.length > 8);
Visual
Lazy vs Eager Flow
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ STATE UPDATE โ
โ count = 5 โโบ (Marked as Dirty) โ
โ โ
โ UI RENDER โ
โ Read Derived โโโบ (Run computation) โโโบ Valueโ
โ โ
โ If UI doesn't read, computation is skipped. โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Dependency Graph
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ State A State B โ
โ โ โ โ
โ โผ โผ โ
โ $derived(A + B) โโโบ Result โ
โ โ โ
โ โผ โ
โ UI Component โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Mechanism | Lazy evaluation |
| Tracking | Automatic via Proxies |
| Immutability | Read-only |
| Memoization | Built-in |
Key takeaways:
$derived()is for computation. Use it to create state that depends on other reactive state.- Lazy by default. Computations only run when the value is read, making it perfect for performance-intensive logic.
- No side effects. Never perform API calls or mutations inside a
$derived()block; that is what$effect()is for. - Memoized. If dependencies have not changed, the computation is skipped, returning the previously cached result.
- Readable. It replaces the confusing
$:syntax with a clear, functional primitive that fits anywhere in your codebase.
Remember: $derived() is the cornerstone of Svelte’s reactive graph. It forces you to define your application logic as a tree of dependencies, where raw state flows upward into increasingly complex, derived values. By embracing this, you move away from tracking mutations manually and instead build a system where the UI naturally flows from your state definitions.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!