Batch Updates
Overview
Batch updates in neutrix let you make multiple state changes in a single operation. This is important for:
- Performance (reduces re-renders)
- State consistency (all changes happen together)
- Atomic operations (all updates succeed or fail together)
Basic Usage
Simple Batch Update
typescript
const useStore = createNeutrixStore({
user: { name: '', email: '' },
preferences: { theme: 'light' }
});
// Update multiple values at once
useStore.store.batch([
['user.name', 'abc'],
['user.email', 'abc@example.com'],
['preferences.theme', 'dark']
]);
2. With Complex State
typescript
interface AppState {
user: {
profile: {
name: string;
email: string;
};
settings: {
theme: 'light' | 'dark';
notifications: boolean;
};
};
lastUpdated: string;
}
const { store } = createNeutrixStore<AppState>({
user: {
profile: { name: '', email: '' },
settings: { theme: 'light', notifications: true }
},
lastUpdated: ''
});
store.batch([
['user.profile.name', 'Jane Doe'],
['user.settings.theme', 'dark'],
['lastUpdated', new Date().toISOString()]
]);
Features
1. Automatic Validation
If you've set up validation in your store options, batch updates will respect it:
typescript
const useStore = createNeutrixStore({
count: 0,
user: null
}, {
validate: (state) => {
if (state.count < 0) return "Count cannot be negative";
return true;
}
});
2. Dependency Tracking
Batch updates work seamlessly with computed values:
typescript
const fullName = useNeutrixComputed(store => {
const firstName = store.get('user.firstName');
const lastName = store.get('user.lastName');
return `${firstName} ${lastName}`;
});
// Single update to computed value
store.batch([
['user.firstName', 'John'],
['user.lastName', 'Doe']
]);
3. Error Handling
If any update in the batch fails, none of the updates will be applied:
typescript
try {
store.batch([
['user.name', 'John'],
['count', -1]
]);
} catch (error) {
console.error('Batch update failed:', error);
}
When you use batch updates like this, all changes are applied together. Your components only re-render once after all updates are complete, rather than updating for each individual change.