Overview
A computed value is a derived state container that automatically tracks its dependencies and recalculates only when those dependencies change. Computed values are lazy - they only run when read AND subscribed to. Computed values:- Automatically track which atoms they depend on
- Only recalculate when dependencies change
- Cache their result until dependencies update
- Are read-only (cannot be set directly)
Creating Computed Values
Basic Usage
Create a computed value with a function:Type Signature
Automatic Dependency Tracking
Computed values automatically track any atoms read during execution:Lazy Evaluation
Computed values are lazy - they only execute when:- They are read (called as a function)
- AND they have subscribers OR are dirty
Conditional Dependencies
Dependencies can be conditional based on runtime logic:Chaining Computed Values
Computed values can depend on other computed values:Reatom efficiently handles dependency chains. Only the necessary computations run when an atom changes.
Derived State Patterns
Filtering
Transformation
Aggregation
Error Handling
Computed values can handle errors in their dependencies:Disconnecting Dependencies
When a computed value is unsubscribed, it automatically disconnects from its dependencies:Comparison with Atoms
Performance Optimization
Memoization
Computed values automatically memoize their results:Avoiding Over-computation
Best Practices
Keep computations pure
Keep computations pure
Computed functions should be pure - no side effects:
Use descriptive names
Use descriptive names
Name computed values based on what they represent:
Avoid expensive computations without subscribers
Avoid expensive computations without subscribers
Remember that computed values are lazy - they won’t run unless subscribed:
Related Concepts
Atom
Create mutable state containers
Actions
Encapsulate logic and side effects
Effects
Run reactive side effects
Extend
Add capabilities with extensions