Skip to main content

Overview

The computed() function creates a derived state container that automatically tracks its dependencies (other atoms or computed values that are called during computation) and only recalculates when those dependencies change. The computation is lazy - it only runs when the computed value is read AND subscribed to.

Import

Signature

Parameters

(() => State) | ((state?: State) => State)
required
A function that computes the derived state. Any atoms or computed values called within this function automatically become dependencies. The function can optionally receive the previous computed state as a parameter.
string
Optional name for the computed atom. Useful for debugging and dev tools. If not provided, an auto-generated name will be used.

Returns

Computed<State>
A computed atom instance with the following interface:

Examples

Basic Derived State

Multiple Dependencies

Conditional Dependencies

Chained Computed Values

Using Previous State

Complex Calculations

Subscribing to Computed Values

Type Information

Computed Interface

Key Characteristics

  • Lazy Evaluation: Computed values only recalculate when read AND when their dependencies have changed
  • Automatic Dependency Tracking: Any atom or computed value called within the computation function is automatically tracked as a dependency
  • Read-Only: Computed atoms cannot be directly modified with .set() - they derive their value from other atoms
  • Efficient: Computed values use memoization to avoid unnecessary recalculations

Performance Tips

  1. Keep computations pure: Computed functions should not have side effects
  2. Conditional dependencies: Only atoms called during execution become dependencies
  3. Subscription matters: Unsubscribed computed atoms recalculate on every read
  4. Chain computations: Break complex calculations into smaller computed atoms for better performance
  • atom() - Create mutable state containers
  • action() - Create logic and side effect containers
  • effect() - Create reactive side effects
  • extend() - Add functionality to computed atoms