State Management
State management is the practice of handling the data flow within an application. As applications grow, managing UI state, server data, and complex interactions becomes challenging without a clear strategy.
Why It Matters
- Predictability: Centralized state makes behavior easier to reason about.
- Scalability: Shared state can be accessed across many components without prop drilling.
- Debugging: Time‑travel debugging and snapshot logging become possible.
Common Patterns
- Local Component State – Using internal state (e.g., React
useState
). - Context API – Provides a light-weight way to share state across a component tree.
- Flux / Redux – A unidirectional data flow with a single immutable store.
- MobX – Reactive observables for automatic UI updates.
- Vuex / Pinia – State containers designed for Vue applications.
React Example with Redux Toolkit
import { configureStore, createSlice } from '@reduxjs/toolkit';
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment: state => { state.value += 1; },
decrement: state => { state.value -= 1; },
addAmount: (state, action) => { state.value += action.payload; }
}
});
export const { increment, decrement, addAmount } = counterSlice.actions;
export const store = configureStore({
reducer: { counter: counterSlice.reducer }
});
Vue Example with Pinia
import { defineStore } from 'pinia';
export const useCartStore = defineStore('cart', {
state: () => ({
items: []
}),
getters: {
itemCount: state => state.items.length,
totalPrice: state => state.items.reduce((sum, i) => sum + i.price * i.qty, 0)
},
actions: {
addItem(product) {
const existing = this.items.find(i => i.id === product.id);
if (existing) existing.qty += 1;
else this.items.push({ ...product, qty: 1 });
},
removeItem(id) {
this.items = this.items.filter(i => i.id !== id);
}
}
});
Best Practices
- Keep the store flat; avoid deeply nested objects.
- Use immutable updates or libraries that handle immutability.
- Separate UI state from server data where possible.
- Leverage TypeScript for better type safety.
- Document actions and reducers for onboarding.