Skip to main content

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:
Use wrap() with promises to make them abortable. When the effect re-runs or is cancelled, wrapped promises are automatically aborted.

Polling Pattern

Effects are perfect for polling data:

Conditional Effects

Effects can run conditionally based on state:

Manual Cleanup

Effects return an unsubscribe 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

Always wrap promises to enable automatic cancellation:
Check for abort errors to distinguish from real errors:
Early returns make conditional logic clearer:

Atom

Store mutable state

Computed

Derive state without side effects

Actions

Imperative operations with parameters

Extend

Customize effect behavior