leptos-store
Enterprise-grade, type-enforced state management for Leptos
Overview
leptos-store provides a structured, SSR-safe state management architecture for Leptos, inspired by Vuex and Pinia, translated into idiomatic Rust.
Leptos provides excellent low-level primitives (signals, context, resources), but intentionally does not define a canonical, scalable state architecture. At scale, this absence can create challenges for large teams, enterprise governance, long-lived applications, SSR safety, and state auditing unless additional architectural patterns are introduced.
leptos-store exists to solve structure, not reactivity.
Features
- 🏗️ Global, namespaced stores - Clear domain boundaries
- 🔒 Predictable mutation flow - Only mutators can write state
- 🌐 First-class SSR support - Works seamlessly with server-side rendering
- 💧 SSR Hydration - Automatic state serialization and hydration between server and client
- ⚡ Async-safe actions - Built-in support for async operations
- 🔧 Compile-time enforcement - Catch errors at compile time, not runtime
- 📦 Zero magic - No hidden executors or runtime reflection
Installation
Add to your Cargo.toml:
[]
= "0.7"
= "0.8"
Feature Flags
| Feature | Default | Description |
|---|---|---|
ssr |
✅ Yes | Server-side rendering support |
hydrate |
❌ No | SSR hydration with automatic state serialization and transfer |
csr |
❌ No | Client-side rendering only (no SSR) |
middleware |
❌ No | Middleware system, audit trail, store coordination |
devtools |
❌ No | DevTools integration with time-travel debugging |
persist-web |
❌ No | Browser-based state persistence (localStorage/sessionStorage) |
Basic Usage (SSR without Hydration)
The ssr feature is enabled by default. For basic SSR without state hydration:
[]
= "0.7"
Full SSR with Hydration (Recommended for Production)
For full SSR applications where state needs to transfer from server to client, enable the hydrate feature. This requires different features for server and client builds:
[]
= { = "0.7", = false }
[]
= ["leptos-store/ssr", "leptos/ssr"]
= ["leptos-store/hydrate", "leptos/hydrate"]
The hydrate feature enables:
HydratableStoretrait for state serializationprovide_hydrated_store()- Server-side state embeddinguse_hydrated_store()- Client-side state recovery- Automatic JSON serialization via
serde
Client-Side Only
For SPAs without server rendering:
[]
= { = "0.7", = false, = ["csr"] }
Deployment Models
| Model | Feature Flag | Description | Best For |
|---|---|---|---|
| SSR | ssr (default) |
Store created per-request on server, HTML rendered with initial state | SEO, fast initial paint |
| Hydrate | hydrate |
Server renders AND serializes state; client picks up seamlessly | Full-stack apps with dynamic data |
| CSR | csr |
Store created once in the browser; no server, no hydration | SPAs, static sites, prototypes |
CSR Quick Start:
use *;
use *;
// In CSR mode, just create and provide — no server needed
let store = new;
provide_store;
// Or use the CSR helper:
// mount_csr_store(store);
Feature flag conflicts:
csrandssrshould not both be enabled.hydrateimpliesssrbehavior on the server side.
Quick Start
Define Your Store (Enterprise Mode)
The library enforces the Enterprise Mode pattern:
- Getters: Public, read-only derived values
- Mutators: Private, internal state modification only
- Actions: Public, the only external API for writes
use *;
use *;
// Define your state
// Define your store
Use in Components
Using the store! Macro
For less boilerplate, use the declarative macro:
use store;
store!
Note: Use
this(or any identifier) instead ofselfin getter/mutator/action bodies due to Rust 2024 macro hygiene rules. The macro providesthis.read()for getters andthis.mutate()for mutators. Mutators are private - external code must use public actions.
Available Macros
| Macro | Purpose | Feature |
|---|---|---|
define_state! |
Define state structs with default values | - |
define_hydratable_state! |
Define state with serde derives for hydration | hydrate |
define_action! |
Define synchronous action structs | - |
define_async_action! |
Define async action structs with result types | - |
impl_store! |
Implement Store trait for an existing type | - |
impl_hydratable_store! |
Implement HydratableStore trait | hydrate |
store! |
Complete store definition in one macro | - |
selector! |
Batch-create multiple selectors from a store | - |
namespace! |
Define typed namespace combining multiple stores | - |
derive_state_diff! |
Generate StateDiff impl for field-level diffing |
middleware |
define_state! - State with Defaults
use define_state;
define_state!
let user = default;
assert_eq!;
assert!;
define_action! - Synchronous Actions
use define_action;
define_action!
let action = new;
define_async_action! - Async Actions with Error Types
use define_async_action;
// Define your error type
// Define the async action
define_async_action!
let action = new;
// Helper methods for documentation
assert!;
assert_eq!;
assert_eq!;
impl_store! - Quick Store Trait Implementation
use *;
use ;
// One-liner to implement Store trait
impl_store!;
Conceptual Model
Each store is a domain module composed of:
| Layer | Description | Can Write State | Async | Side Effects |
|---|---|---|---|---|
| State | Read-only externally | N/A | ❌ | ❌ |
| Getters | Derived, read-only | ❌ | ❌ | ❌ |
| Mutators | Pure, synchronous writes | ✅ | ❌ | ❌ |
| Actions | Sync orchestration | ❌ | ❌ | ✅ |
| Async Actions | Async orchestration | ❌ | ✅ | ✅ |
Only mutators may write state. This is the core principle that ensures predictability.
Advanced Usage
Async Actions
use *;
Lifecycle: Every async action follows: Idle → Pending → Success | Error
- Idle: Initial state, no operation in progress
- Pending: Operation dispatched, awaiting result; use for loading indicators
- Success: Operation completed; result available via
ActionHandle - Error: Operation failed; error available for display or retry
Loading state in components:
let handle = store.dispatch_async;
view!
Cancellation: Call handle.cancel() to abort an in-flight async action. The state transitions to Idle and any pending future is dropped.
Selectors — Fine-Grained Reactivity
Selectors create memoized views into specific slices of store state. Unlike reading the full state signal, selectors only trigger re-renders when their particular slice changes.
use *;
let store = ;
// Extract a single slice — only re-computes when user_name changes
let user_name = create_selector;
// Combine two selectors into a derived value
let item_count = create_selector;
let discount = create_selector;
let total = combine_selectors;
// Transform a selector's output
let badge = map_selector;
// Only propagate when a condition is met
let active_items = filter_selector;
// Returns Memo<Option<usize>> — None when cart is empty
Batch declaration with selector! macro:
selector!
// Generates: let user_name: Memo<String>, let is_admin: Memo<bool>, etc.
Scoped Stores
For multiple instances of the same store type:
// Provide scoped stores with unique IDs
;
;
// Access scoped stores
let counter1 = ;
let counter2 = ;
Multiple Namespaced Stores
For large applications with many domain stores, use the namespace! macro to create a typed container with generated context helpers:
use namespace;
namespace!
// Generated API:
// AppStores::new(user, products, cart, orders, ui)
// app_stores.user() -> &UserStore
// provide_app_stores(stores) — wraps provide_context
// use_app_stores() -> AppStores — wraps use_context
Domain boundary guidelines:
- One domain = one store —
UserStoreowns auth + profile + preferences - Stores communicate via
StoreCoordinator, not direct references - Shared state (theme, locale) goes in a
UiStore; domain-specific state stays in its own store - Module organization:
stores/user/mod.rs,stores/cart/mod.rs, etc.
Audit Trail (requires middleware feature)
Track every state mutation with field-level diffs, user context, and state replay:
use *;
// Create audit trail
let audit = new
.with_max_entries
.with_user_context;
// Record a mutation with automatic diff
let before = old_state.clone;
let after = new_state.clone;
audit.record_with_diff;
// Query audit entries
let recent = audit.entries_since;
let profile_changes = audit.entries_for_mutation;
// Replay: get state at any point in history
let historical_state = audit.state_at;
Field-level diffs with derive_state_diff!:
use derive_state_diff;
derive_state_diff!
// Generates StateDiff impl — diff() returns Vec<FieldChange>
// Each FieldChange has: field_path, old_value, new_value, change_type
Cross-Store Coordination (requires middleware feature)
Coordinate reactive dependencies between stores with StoreCoordinator:
use *;
let mut coordinator = new;
// When auth store changes, clear the inventory cache
coordinator.on_change;
// When a specific mutation fires, react in another store
coordinator.on_mutation;
// Start listening after all rules are registered
coordinator.activate;
The coordinator is stateless (just rules) — on hydration, re-register the same rules client-side.
Store Registry
For debugging and hot-reloading:
let mut registry = new;
registry.register?;
// Later...
let store = registry.;
SSR Hydration
For full SSR applications, implement HydratableStore to enable automatic state transfer from server to client:
use *;
use *;
use ;
// State must derive Serialize and Deserialize
// Implement HydratableStore for SSR hydration
Or use the impl_hydratable_store! macro for less boilerplate:
use impl_hydratable_store;
impl_hydratable_store!;
Server-side (SSR):
// Provide store and render hydration script
let store = new_with_data;
let hydration_script = provide_hydrated_store;
view!
Client-side (Hydration):
// Automatically hydrate from server-rendered state
let store = ;
Design Philosophy
Convention over Primitives
Instead of giving you raw signals and hoping for the best, leptos-store provides a structured architecture that scales.
Compile-time Enforcement
The type system prevents invalid state transitions. If it compiles, it follows the rules.
SSR-First Design
Every feature is designed with server-side rendering in mind. No hydration mismatches.
Examples
See the examples/ directory for complete examples:
counter-example- Simple counter using thestore!macro with increment/decrementauth-store-example- User authentication flow with login/logouttoken-explorer-example- Full SSR with hydration - Real-time Solana token explorer using Jupiter APIcsr-example- CSR-only todo list demonstrating client-side store initializationselectors-example- Fine-grained reactivity with selectors, combinators, and theselector!macromiddleware-example- Middleware pipeline with logging, validation, and event buscomposition-example- Multi-store composition withRootStorebuilderpersistence-example- State persistence across page reloadsfeature-flags-example- Feature flag management storedevtools-example- DevTools integration with time-travel debugging
Running Examples
# List all available examples
# Run a specific example (SSR mode with cargo-leptos)
# Build an example
Token Explorer Example
The token-explorer-example demonstrates full SSR hydration:
- 🌐 Server-side data fetching from Jupiter API
- 💧 Automatic state hydration to client
- 🔄 Client-side polling for real-time updates
- 🔍 Reactive filtering and sorting
- 🎨 Beautiful token card UI
# Run the token explorer
# Opens at http://127.0.0.1:3005
Contributing
We welcome contributions! See AUTHORING.md for:
- Development setup and workflow
- Project structure and architecture
- Testing and code quality guidelines
- Publishing releases
# Quick start for contributors
License and Attribution
leptos-store is licensed under the Apache License, Version 2.0.
You are free to use, modify, and distribute this software, including for commercial purposes, provided that you retain the license text and the NOTICE file as required by the Apache 2.0 License.
This software is provided "AS IS", without warranty of any kind. The author is not liable for any damages arising from its use.