KB Home

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

Common Patterns

  1. Local Component State – Using internal state (e.g., React useState).
  2. Context API – Provides a light-weight way to share state across a component tree.
  3. Flux / Redux – A unidirectional data flow with a single immutable store.
  4. MobX – Reactive observables for automatic UI updates.
  5. 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

Further Reading

Redux DocumentationPinia DocsReact State Overview