Overview
Effects are reactive side effects that automatically track their dependencies and clean themselves up when dependencies change or when the effect is aborted. They’re designed for running side effects in response to state changes. Effects:- Automatically track atom dependencies
- Re-run when dependencies change
- Support async operations with abort handling
- Clean up automatically on context abort
- Return an unsubscribe function for manual cleanup
Creating Effects
Basic Usage
Type Signature
Automatic Dependency Tracking
Effects automatically track any atoms read during execution:Effects automatically subscribe and start running immediately upon creation.
Async Effects
Effects work seamlessly with async operations:Polling Pattern
Effects are perfect for polling data:Conditional Effects
Effects can run conditionally based on state:Manual Cleanup
Effects return anunsubscribe function for manual cleanup:
Effect Lifecycle
Effects automatically handle cleanup when context is aborted:Common Patterns
Local Storage Sync
Document Title
WebSocket Connection
Scroll to Top
Auto-save
Effects vs Actions
Effects vs Computed
Abort Handling
Effects integrate with Reatom’s abort system:Best Practices
Use wrap() for abortable async operations
Use wrap() for abortable async operations
Always wrap promises to enable automatic cancellation:
Handle abort errors gracefully
Handle abort errors gracefully
Check for abort errors to distinguish from real errors:
Use guard clauses for conditional effects
Use guard clauses for conditional effects
Early returns make conditional logic clearer:
Related Concepts
Atom
Store mutable state
Computed
Derive state without side effects
Actions
Imperative operations with parameters
Extend
Customize effect behavior