Skip to main content

State Persistence

Reatom provides a powerful persistence system that automatically synchronizes atom state with various storage backends, including localStorage, sessionStorage, IndexedDB, and custom storage implementations.

Core Concepts

Reatom’s persistence system offers:
  • Automatic Synchronization - State syncs to storage on every change
  • Cross-Tab Sync - Changes in one tab update other tabs automatically
  • Schema Validation - Validate persisted data with Standard Schema
  • Versioning & Migration - Handle schema changes gracefully
  • TTL Support - Automatically expire old data
  • Custom Storage - Implement any storage backend

Quick Start

LocalStorage Persistence

SessionStorage Persistence

Storage Options

LocalStorage

Persists data between browser sessions:
Features:
  • ~5-10MB storage limit (varies by browser)
  • Shared across all tabs
  • Cross-tab synchronization via storage events
  • Automatic fallback to memory storage if unavailable

SessionStorage

Persists data for the current session only:
Features:
  • ~5-10MB storage limit (varies by browser)
  • Isolated per tab (no cross-tab sharing)
  • Cleared when tab closes
  • Automatic fallback to memory storage if unavailable

IndexedDB

Store large amounts of structured data:
Features:
  • Much larger storage limits (often 50MB+)
  • Async operations (non-blocking)
  • Supports complex data structures
  • Cross-tab synchronization

Cookies

Store small amounts of data that need server access:
Features:
  • ~4KB size limit per cookie
  • Sent with HTTP requests
  • Can set expiration, domain, path
  • Useful for SSR applications

Advanced Configuration

State Transformation

Transform data before persisting:

Schema Validation

Validate persisted data with schemas:

Versioning & Migration

Handle breaking changes with versions:

Time-To-Live (TTL)

Automatically expire data:

Cross-Tab Synchronization

Automatic Sync

LocalStorage automatically syncs across tabs:

Disable Sync

Disable cross-tab synchronization:

Custom Storage

Creating Custom Storage

Async Storage

Implement async storage backends:

Memory Storage

In-memory storage for testing:

Best Practices

1. Use Appropriate Storage

Choose the right storage for your use case:

2. Always Validate Persisted Data

Never trust persisted data:

3. Use Versioning for Production

Always version your schemas:

4. Set Appropriate TTLs

Don’t store data forever:
Security Warning: Never persist sensitive data like passwords or auth tokens in localStorage or sessionStorage. Use httpOnly cookies or secure server-side sessions instead.

Common Patterns

Persist Partial State

Only persist specific fields:

Lazy Hydration

Defer hydration until needed:

Conditional Persistence

Persist based on conditions:

Encrypted Storage

Encrypt sensitive data:

Testing

Mock Storage

Reset Between Tests