State Persistence
Overview
Neutrix can persist your store's state to localStorage, allowing it to survive page reloads. When enabled, your state automatically saves and restores between sessions.
Basic Usage
1. Simple persistence
The simplest way to enable persistence is by passing the persist option when creating your store:
typescript
import { createNeutrixStore } from 'neutrix';
const useStore = createNeutrixStore(
{
user: null,
settings: {
theme: 'light',
notifications: true
}
},
{
persist: true, // enable persistence
name: 'my-store'
}
);
Selective Persistence
Use a custom function to store only certain fields:
typescript
const useStore = createNeutrixStore(
{
user: null,
settings: { theme: 'light' },
tempData: { searchResults: [] }
},
{
persist: (state) => ({
// only persist these fields
user: state.user,
settings: state.settings
}),
name: 'my-store'
}
);
Tip: Exclude transient UI state (like search results) to avoid cluttering your persisted storage.
State Migration
typescript
const useStore = createNeutrixStore(
{
user: null,
settings: { theme: 'light' }
},
{
persist: true,
name: 'my-app',
migration: {
version: 2,
migrate: (oldState) => {
if (!oldState.__version || oldState.__version < 2) {
return {
...oldState,
settings: {
...oldState.settings,
notifications: true
}
};
}
return oldState;
}
}
}
);
State Validation
typescript
const useStore = createNeutrixStore(
{
count: 0,
user: null
},
{
persist: true,
validate: (state) => {
if (state.count < 0) return "Count cannot be negative";
if (state.user && !state.user.id) return "Invalid user data";
return true;
}
}
);
Error Handling
Neutrix handles persistence errors gracefully:
- Invalid stored data → Falls back to initial state
- Failed migrations → Falls back to initial state
- Failed validation → Falls back to initial state
- Storage errors → Logs a warning, continues with initial state