| | |

Svelte 13 ๐Ÿงก Multi-Statement Derived Logic with $derived.by()

โฑ๏ธ Estimated read: 8 min | |

In complex Svelte applications, not every piece of derived state can be condensed into a single expression. You often encounter scenarios where you must perform multi-step data processing, declare intermediate variables, or execute complex conditional logic before arriving at a final value. While the standard $derived() rune is excellent for simple expressions, $derived.by() is specifically designed for these multi-statement, logic-heavy derivations. By wrapping your logic in a callback function, you gain the ability to use local scope, early returns, and imperative steps, all while maintaining the same high-performance, lazy-evaluating reactivity as the standard rune.

This chapter explores how $derived.by() expands the possibilities of computed state. We will examine the closure-based syntax, the benefits of local scoping for complex algorithms, and how this rune integrates seamlessly with Svelteโ€™s dependency tracking system. By using $derived.by(), you move away from messy, inline ternaries and towards clean, readable, and highly maintainable business logic.

Key point: $derived.by() accepts a callback function that returns the computed value, allowing you to use multiple statements, local variables, and complex control flow to derive reactive state while ensuring dependency tracking remains intact.


Why exists

The single-expression constraint. Standard $derived() is limited by the structure of JavaScript expressions. $derived.by() removes this barrier by allowing full block-level statements, essential for complex transformations.

The readability of intermediate variables. When a computation requires three or four steps to reach a final result, putting them into one massive, unreadable ternary operator is a recipe for maintenance nightmares. $derived.by() allows you to break these into clear, named local variables.

The need for conditional flow control. Simple expressions don’t handle early exits or nested if/else logic gracefully. $derived.by() treats the derivation as a standard function body, enabling clear, procedural logic.

The dependency tracking integrity. Because Svelteโ€™s reactivity engine is runtime-based, it can track dependencies inside a $derived.by() function just as easily as in a single-line expression, ensuring your complex logic remains perfectly reactive.

The performance trade-off. By keeping multi-step logic inside a derived primitive rather than re-calculating it in the DOM or inside an $effect, you ensure that the heavy work is only done when the underlying state actually changes.


a. Syntax and the Closure Pattern

The syntax for $derived.by() is straightforward: it takes a function that returns the value you want to derive. This function is treated as a closure. When you access the derived variable, Svelte executes this function, tracks the reactive properties accessed inside, and caches the result.

let base = $state(100);

let status = $derived.by(() => {
  const result = base * 0.5;
  if (result > 40) return "high";
  return "low";
});

Because this is a function, you have total control over the execution flow. The variables result and the conditions defined within the block are local to the derivation and do not leak into the surrounding scope, keeping your component logic encapsulated.

b. Multi-step Logic and Intermediate Variables

One of the primary benefits of $derived.by() is the ability to break down a complex formula into readable segments. In a standard derivation, you might be tempted to nest ternary operators, which makes the code brittle and difficult to debug. With $derived.by(), you can document your process using intermediate variables.

let cart = $state({ items: [], discountCode: "SAVE20" });

let finalPrice = $derived.by(() => {
  const subtotal = cart.items.reduce((acc, i) => acc + i.price, 0);
  const discount = cart.discountCode === "SAVE20" ? 0.2 : 0;
  return subtotal * (1 - discount);
});

This approach is not just cleaner; it is easier to test. If the logic for finalPrice is incorrect, you can easily inspect the intermediate subtotal or discount values, something that is nearly impossible when your logic is buried inside a complex, inline expression.

c. Complex Branching and Early Exits

When your derivation has complex business rulesโ€”such as handling empty states, specific user permissions, or fallback valuesโ€”multi-line logic becomes mandatory. $derived.by() allows you to use return statements to exit the derivation early, reducing the need for deeply nested conditional structures.

let user = $state({ role: "guest", profile: null });

let permissions = $derived.by(() => {
  if (user.role === "admin") return ["read", "write", "delete"];
  if (!user.profile) return ["read"];
  return ["read", "write"];
});

This declarative style of handling logic is much more robust than trying to pack all these rules into a single $derived() expression. It allows your derived state to reflect the reality of your application’s domain logic accurately and readably.


Complete Example Session

// ============================================
// PART 1: SIMPLE MULTI-STEP MATH
// ============================================
let x = $state(10);
let val = $derived.by(() => {
  let step1 = x * 2;
  let step2 = step1 + 5;
  return step2;
});

// ============================================
// PART 2: EARLY RETURN PATTERN
// ============================================
let input = $state("");
let validated = $derived.by(() => {
  if (input.length === 0) return "Empty";
  if (input.length < 5) return "Too Short";
  return "Valid";
});

// ============================================
// PART 3: OBJECT CONSTRUCTION
// ============================================
let name = $state("Alice");
let config = $derived.by(() => {
  const meta = { id: 1, ts: Date.now() };
  return { ...meta, name };
});

// ============================================
// PART 4: ARRAY TRANSFORMATION
// ============================================
let list = $state([1, 2, 3]);
let stats = $derived.by(() => {
  const sum = list.reduce((a, b) => a + b, 0);
  const avg = sum / list.length;
  return { sum, avg };
});

// ============================================
// PART 5: EXTERNAL MODULE LOGIC
// ============================================
// import { getBase } from './math.js'
let factor = $state(2);
let result = $derived.by(() => {
  const base = getBase(); 
  return base * factor;
});

// ============================================
// PART 6: NESTED OBJECT ACCESS
// ============================================
let data = $state({ user: { settings: { level: 5 } } });
let level = $derived.by(() => {
  const l = data.user.settings.level;
  return l > 10 ? "Pro" : "Basic";
});

// ============================================
// PART 7: CONDITIONALLY CALCULATING
// ============================================
let mode = $state("fast");
let configVal = $derived.by(() => {
  if (mode === "fast") return 100;
  return 50;
});

// ============================================
// PART 8: LOCAL SCOPE VARIABLES
// ============================================
let seed = $state(1);
let hash = $derived.by(() => {
  const salt = "salty";
  return `${salt}:${seed}`;
});

// ============================================
// PART 9: DATA CLEANING
// ============================================
let raw = $state("  svelte  ");
let clean = $derived.by(() => {
  const trimmed = raw.trim();
  return trimmed.toUpperCase();
});

// ============================================
// PART 10: COMPLEX ERROR HANDLING
// ============================================
let val = $state(null);
let display = $derived.by(() => {
  try {
    if (val === null) throw new Error();
    return val.toString();
  } catch {
    return "N/A";
  }
});

These examples demonstrate how $derived.by() acts as a flexible, block-based logic container for your reactive calculations.


Quick Reference

Comparison: $derived() vs $derived.by()

Feature$derived()$derived.by()
SyntaxExpressionClosure (function)
Multi-statementNoYes
Local variablesNoYes
Early returnNoYes
PerformanceIdentical (Lazy)Identical (Lazy)

Usage Patterns

PatternBest For
Ternary chain$derived()
Math formula$derived()
Multi-step algorithm$derived.by()
Complex validation$derived.by()
Early exits$derived.by()

Best Practices

โœ… Do This:

// Break down complex logic
let status = $derived.by(() => {
  const score = calculate(raw); // โœ… Clean local scope
  return score > 10 ? 'A' : 'B';
});

// Use for early exits
let label = $derived.by(() => {
  if (!data) return 'Loading'; // โœ… Clear control flow
  return data.title;
});

โŒ Don’t Do This:

// Massive ternary expression
let status = $derived(x ? (y ? z : w) : (a ? b : c)); // โŒ Hard to read

// Side effects inside derivation
let x = $derived.by(() => { 
  log(); // โŒ Never perform side effects!
  return 1; 
});

Common Pitfalls

PitfallWhy It HappensFix
Side EffectsDeriving acts like an effectUse $effect for logging/API
ComplexityLogic becomes too longMove to a helper function
Dependency LossIncorrect usage of closuresAccess state inside the body
ReassignmentTrying to mutate the returnAlways return a new value

Real-World Examples

1. Form Validation logic

let isValid = $derived.by(() => {
  if (email.length < 5) return false;
  if (!email.includes('@')) return false;
  return true;
});

2. Weighted Score Algorithm

let score = $derived.by(() => {
  const base = inputs.reduce((a, b) => a + b, 0);
  return base * multiplier + offset;
});

3. User Role Hierarchies

let canAccess = $derived.by(() => {
  if (user.isSuper) return true;
  if (user.isModerator && resource.isPublic) return true;
  return false;
});

4. Formatting Currency

let displayPrice = $derived.by(() => {
  const amount = price / 100;
  return `$${amount.toFixed(2)}`;
});

5. Data Normalization

let normalized = $derived.by(() => {
  const data = raw.map(i => i.toLowerCase());
  return [...new Set(data)];
});

6. Dynamic API Config

let endpoint = $derived.by(() => {
  const base = "https://api.com";
  const path = env === "prod" ? "/v1" : "/dev";
  return `${base}${path}`;
});

7. Inventory Stock Status

let stockStatus = $derived.by(() => {
  if (qty === 0) return "Out of Stock";
  if (qty < 5) return "Low Stock";
  return "Available";
});

8. Date Range Logic

let isOverdue = $derived.by(() => {
  const now = Date.now();
  return dueDate < now && !isCompleted;
});

9. Search Result Limit

let viewable = $derived.by(() => {
  return list.slice(0, limit).filter(i => i.visible);
});

10. Multi-part Hash Generation

let hash = $derived.by(() => {
  const key = `${id}:${salt}`;
  return btoa(key);
});

Visual

Closure-Based Logic Flow

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  $derived.by(() => {                         โ”‚
โ”‚     const step1 = x * 2;   <โ”€โ”€ Local scoped  โ”‚
โ”‚     const step2 = step1 + 5;                 โ”‚
โ”‚     return step2;          <โ”€โ”€ Output value  โ”‚
โ”‚  })                                          โ”‚
โ”‚                                              โ”‚
โ”‚  Computation is lazy and cached              โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Branching Logic Comparison

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  STANDARD $derived()                         โ”‚
โ”‚  x ? (y ? 1 : 2) : 3   <โ”€โ”€ Fragile logic     โ”‚
โ”‚                                              โ”‚
โ”‚  $derived.by()                               โ”‚
โ”‚  if (x) {                                    โ”‚
โ”‚     if (y) return 1;                         โ”‚
โ”‚     return 2;                                โ”‚
โ”‚  }                                           โ”‚
โ”‚  return 3;             <โ”€โ”€ Robust logic      โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
MechanismClosure-based computation
Best ForMulti-statement logic
TrackingAutomatic via dependencies
PerformanceLazy, memoized

Key takeaways:

  • $derived.by() is for complexity. When a derivation needs more than one line of code to reach its conclusion, this is your go-to rune.
  • Use local variables. You can now document your calculations using named intermediate variables, greatly improving readability.
  • Support early returns. The function-based structure allows for clean, early-exit control flow that simplifies complex rule sets.
  • Respect the rules of reactivity. Even though it looks like a function, it is still a derivation. Do not perform side effects inside it; use it only to compute values.
  • Performance is preserved. Like standard $derived(), this is lazy and cached, ensuring your complex block logic doesn’t rerun unless dependencies change.

Remember: $derived.by() is about empowering developers to write clean, maintainable logic for complex UI state. By moving from one-line ternary hell to structured, procedural function bodies, you ensure that your Svelte code remains scalable and understandable, even as your business requirements grow in complexity.

Was this helpful?


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!