Managing State

Updated · 10 min read
hardES2026javascriptstate-managementarchitectureimmutability

State is all the data an application remembers while it runs: the list of payments, which filter is selected, whether a dialog is open, the error message to show. State management is how that data is stored, changed and reflected in the page. When state is scattered (some in variables, some in the DOM, some in several components' copies), the page shows contradictory information and bugs multiply. The cure is a few principles that every modern framework follows: one source of truth, changes through defined actions, immutable updates, and the UI rendered from state.

In One Minute

  • Keep each piece of data in one place (the store); everything else reads from it.
  • Change state only through named actions, so every change is easy to find and log.
  • Update immutably: create new objects instead of changing old ones, so changes are easy to detect and undo.
  • Render the UI from state: render(state) turns data into DOM; never treat the DOM as the data.
  • Derive computed values (totals, filtered lists) instead of storing them.

The Problem: Scattered State

scattered.js
// State in three places that can disagree:
let total = 0;                                     // a variable
document.querySelector("#count").textContent = 3;  // the DOM
students[1].balance = 0;                           // an object other code shares
 
// Later someone updates one and forgets the others: the page shows 3 students
// and a total that no longer matches the list.

Every duplicated piece of data is a chance for the copies to disagree.

One Source of Truth

Put all shared data in one store object with a small interface: read the state, dispatch actions to change it, and subscribe to changes:

store.js▶ Try it
function createStore(reducer, initialState) {
  let state = initialState;
  const listeners = new Set();
  return {
    getState: () => state,
    dispatch(action) {
      state = reducer(state, action);
      for (const listener of listeners) listener(state, action);
    },
    subscribe(listener) {
      listeners.add(listener);
      return () => listeners.delete(listener);
    },
  };
}
 
function reducer(state, action) {
  switch (action.type) {
    case "payment/added":
      return { ...state, payments: [...state.payments, action.payment] };
    case "payment/removed":
      return { ...state, payments: state.payments.filter((p) => p.id !== action.id) };
    case "filter/changed":
      return { ...state, filter: action.filter };
    default:
      return state;
  }
}
 
const store = createStore(reducer, { payments: [], filter: "all" });
store.subscribe((state, action) => console.log(`${action.type} -> ${state.payments.length} payments, filter ${state.filter}`));
 
store.dispatch({ type: "payment/added", payment: { id: 1, name: "Navika", amount: 120 } });
store.dispatch({ type: "payment/added", payment: { id: 2, name: "Advitha", amount: 45 } });
store.dispatch({ type: "filter/changed", filter: "large" });
store.dispatch({ type: "payment/removed", id: 1 });
Output
payment/added -> 1 payments, filter all
payment/added -> 2 payments, filter all
filter/changed -> 2 payments, filter large
payment/removed -> 1 payments, filter large

Explanation: the reducer is a pure function (state, action) => newState that describes every possible change in one place. Actions are plain objects naming what happened. The store runs the reducer and notifies subscribers. This is the Redux pattern, and also the idea behind React's useReducer.

PartRole
StateOne object holding all shared data
Action{ type: "payment/added", payment }: what happened
ReducerPure function computing the next state
StoreHolds state, runs the reducer, notifies subscribers
SubscribersUI code that re-renders when state changes

Immutable Updates

The reducer never changes the old state; it returns new objects for the parts that changed and reuses the rest. Benefits:

  • Change detection is cheap: old.payments !== new.payments means the list changed; no deep comparison needed.
  • History is free: keeping old states enables undo, redo and debugging tools that "time travel".
  • No surprise changes: code holding an old reference isn't affected by updates.
immutable.js▶ Try it
const before = { payments: [{ id: 1, amount: 120 }, { id: 2, amount: 45 }], settings: { currency: "USD" } };
 
const after = {
  ...before,
  payments: before.payments.map((p) => (p.id === 2 ? { ...p, amount: 50 } : p)),
};
 
console.log(before.payments[1].amount, after.payments[1].amount);
console.log("payments changed:", before.payments !== after.payments);
console.log("settings reused:", before.settings === after.settings);
console.log("payment 1 reused:", before.payments[0] === after.payments[0]);
Output
45 50
payments changed: true
settings reused: true
payment 1 reused: true

Only the changed path (the payments array and payment 2) is new; everything else is shared. This structural sharing keeps immutable updates cheap.

Render from State

The UI should be a function of state: given the state, render produces the right page. After any change, re-render from the new state, rather than patching the DOM by hand in many places:

render.html
<button id="add">Add payment</button>
<button data-filter="all">All</button><button data-filter="large">Large only</button>
<p id="summary"></p>
<ul id="list"></ul>
<script type="module">
  let state = { payments: [], filter: "all", nextId: 1 };
  const amounts = [120, 45];

  function dispatch(action) {
    if (action.type === "add") {
      const amount = amounts[(state.nextId - 1) % amounts.length];
      state = { ...state, nextId: state.nextId + 1, payments: [...state.payments, { id: state.nextId, amount }] };
    }
    if (action.type === "filter") state = { ...state, filter: action.filter };
    render(state);
  }

  const visible = (s) => (s.filter === "large" ? s.payments.filter((p) => p.amount >= 100) : s.payments);

  function render(s) {
    const shown = visible(s);
    document.querySelector("#list").replaceChildren(...shown.map((p) => Object.assign(document.createElement("li"), { textContent: `#${p.id}: $${p.amount}` })));
    document.querySelector("#summary").textContent = `${shown.length} of ${s.payments.length} shown (${s.filter})`;
    console.log(document.querySelector("#summary").textContent);
  }

  document.querySelector("#add").addEventListener("click", () => dispatch({ type: "add" }));
  document.addEventListener("click", (e) => {
    const f = e.target.closest("[data-filter]");
    if (f) dispatch({ type: "filter", filter: f.dataset.filter });
  });
  render(state);
</script>
Output
0 of 0 shown (all)
1 of 1 shown (all)
2 of 2 shown (all)
1 of 2 shown (large)

The DOM is never the source of truth: the list and the summary are always computed from state, so they can't disagree. Re-rendering a whole list is fine for small lists; frameworks update only the elements that changed, which is the main thing they add.

Derive, Don't Store

Values that can be computed from other state (totals, counts, filtered lists, "is the form valid?") should be derived when needed, not stored separately, or they will eventually go stale:

derived.js▶ Try it
const state = { payments: [{ name: "Navika", amount: 120 }, { name: "Advitha", amount: 45 }, { name: "Navika", amount: 60 }] };
 
const selectors = {
  total: (s) => s.payments.reduce((sum, p) => sum + p.amount, 0),
  count: (s) => s.payments.length,
  byStudent: (s) => Object.fromEntries(Object.entries(Object.groupBy(s.payments, (p) => p.name)).map(([n, ps]) => [n, ps.reduce((a, p) => a + p.amount, 0)])),
};
 
console.log(selectors.total(state), selectors.count(state), selectors.byStudent(state));
Output
225 3 { Navika: 180, Advitha: 45 }

Functions that compute values from state are called selectors. If a derivation is expensive, memoize it (recompute only when its input objects change, which immutable updates make easy to detect).

What Belongs Where

Kind of stateExampleWhere
Server dataPayments, studentsA store or data cache, loaded through the data layer
UI state shared by several partsSelected student, current filterThe store
Local UI stateWhether one dropdown is open, text in an unsaved inputThe component itself
URL stateSearch query, current page, filters worth sharingThe URL (URLSearchParams, see "Window, Location and History")
Persistent preferencesTheme, page sizelocalStorage, loaded into the store at startup
Derived valuesTotals, countsComputed by selectors

Persisting State

Subscribing to the store makes saving automatic. Save only what should survive a reload, and validate it when loading:

persist.js▶ Try it
const memoryStorage = new Map();
const storage = { getItem: (k) => memoryStorage.get(k) ?? null, setItem: (k, v) => memoryStorage.set(k, v) };
 
function loadPreferences() {
  try {
    const saved = JSON.parse(storage.getItem("feeTracker.prefs") ?? "{}");
    return { pageSize: Number.isInteger(saved.pageSize) ? saved.pageSize : 25, theme: saved.theme === "dark" ? "dark" : "light" };
  } catch {
    return { pageSize: 25, theme: "light" };
  }
}
 
let prefs = loadPreferences();
const savePreferences = (p) => storage.setItem("feeTracker.prefs", JSON.stringify(p));
 
prefs = { ...prefs, theme: "dark" };
savePreferences(prefs);
console.log(loadPreferences());
Output
{ pageSize: 25, theme: 'dark' }

(This example uses a Map in place of localStorage so it runs anywhere; in a browser, pass localStorage instead, the same interface.)

How Frameworks Solve the Same Problem

Framework ideaSame principle as
React: useState, useReducer, Redux, ZustandStore, actions, reducers, immutable updates
Angular: signals, services, NgRxReactive values that notify dependents; reducers
Vue: reactive, ref, PiniaProxies that detect changes (see "Proxy and Reflect")
Svelte, Solid: signals and runesFine-grained values that update exactly the DOM that uses them
All of themRender the UI from state; derive computed values

Signals deserve a mention: a signal is a value that knows who reads it and notifies only those readers when it changes, so updates touch exactly the affected parts of the page. Several frameworks are built on them, and an early-stage TC39 proposal explores adding signals to JavaScript itself.

In Practice

The Fee Tracker's store adds two conveniences on top of the basic pattern: undo (free, thanks to immutability) and an action log for debugging:

undo.js▶ Try it
function createUndoableStore(reducer, initial) {
  let past = [];
  let present = initial;
  const log = [];
  return {
    get: () => present,
    dispatch(action) {
      past = [...past, present];
      present = reducer(present, action);
      log.push(action.type);
    },
    undo() {
      if (past.length === 0) return;
      present = past.at(-1);
      past = past.slice(0, -1);
      log.push("undo");
    },
    log: () => log.join(", "),
  };
}
 
const reducer = (s, a) => (a.type === "pay" ? { ...s, balance: s.balance - a.amount } : s);
const store = createUndoableStore(reducer, { name: "Srihitha", balance: 450 });
 
store.dispatch({ type: "pay", amount: 200 });
store.dispatch({ type: "pay", amount: 500 });
console.log(store.get().balance);
store.undo();
console.log(store.get().balance, "|", store.log());
Output
-250
250 | pay, pay, undo

The mistaken $500 payment pushed the balance negative; undo restored the previous state exactly, because old states were never modified. (A real reducer would also reject an overpayment.)

Common Mistakes

Keeping data in the DOM. Reading values back from elements to compute things leads to drift. Keep data in state; render it.

Mutating state in place. Subscribers can't tell what changed, and history breaks. Return new objects.

Storing derived values. Totals stored next to the list go stale. Compute them with selectors.

One global store for everything. Local UI details (is this menu open?) don't belong in shared state.

Practice

Challenge: Write a reducer for a to-do list with actions todo/added (with text), todo/toggled (with id) and todo/cleared (removes completed items), and run a sequence of actions.

Show solution
todo-reducer.js▶ Try it
function todos(state = [], action) {
  switch (action.type) {
    case "todo/added":
      return [...state, { id: state.length ? state.at(-1).id + 1 : 1, text: action.text, done: false }];
    case "todo/toggled":
      return state.map((t) => (t.id === action.id ? { ...t, done: !t.done } : t));
    case "todo/cleared":
      return state.filter((t) => !t.done);
    default:
      return state;
  }
}
 
let state = todos(undefined, { type: "init" });
for (const action of [
  { type: "todo/added", text: "Email Navika's receipt" },
  { type: "todo/added", text: "Remind Advitha" },
  { type: "todo/toggled", id: 1 },
  { type: "todo/cleared" },
]) state = todos(state, action);
console.log(state);
Output
[{ id: 2, text: 'Remind Advitha', done: false }]

Quick check: Managing state

3 questions
1What is a reducer?
2Why update state immutably?
3Should a payment total be stored in state next to the payments?

Key Takeaways

ConceptCode
Action{ type: "payment/added", payment }
Reducer(state, action) => newState
Immutable update{ ...state, payments: [...state.payments, p] }
Subscribestore.subscribe((state) => render(state))
Selectorconst total = (s) => s.payments.reduce(...)

Was this tutorial helpful?

Lesson 132 of 139