Advanced State Management

Published by Brayan K

State management is the discipline of keeping your application's data consistent and predictable — using a single source of truth, the observer pattern, immutable updates, and reducers, which are the same ideas that power libraries like Redux and Zustand, implemented here in plain JavaScript.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

State is authoritative data; a view is a projection

A central store earns its complexity when several consumers need the same state and consistent update rules. It is not required for every local input. Keep the authoritative data small and derive values such as totals or filtered lists instead of storing duplicate copies that can disagree.

const state = Object.freeze({
  tasks: Object.freeze([
    Object.freeze({ id: 1, done: false }),
    Object.freeze({ id: 2, done: true })
  ])
});
const selectOpenCount = state => state.tasks.filter(task => !task.done).length;
console.log(selectOpenCount(state));
console.log(state.tasks.length);

// ✅ Expected output:
// 1
// 2

A selector reads state without changing it. A reducer computes the next state from the previous state and an action. A store owns the current reference and the subscription policy. Rendering, network requests and persistence are effects outside the reducer. Separating those responsibilities makes a failed effect distinguishable from a failed state transition.

Immutable updates preserve unchanged references intentionally

const before = [{ id: 1, done: false }, { id: 2, done: false }];
const copied = before.slice();
copied[0].done = true;
console.log(before[0].done, copied !== before, copied[0] === before[0]);

// ✅ Expected output:
// true true true
const before = [{ id: 1, done: false }, { id: 2, done: false }];
const after = before.map(task => task.id === 2 ? { ...task, done: true } : task);
console.log(before[1].done, after[1].done);
console.log(before === after, before[0] === after[0], before[1] === after[1]);

// ✅ Expected output:
// false true
// false true false

Reference equality is useful only when the update contract is honored. A selector that memoizes by state identity can return stale data if someone mutates a nested object in place. Object.freeze is shallow; the flat counter state below contains only numbers, so freezing that record covers its whole exposed value. It is not a generic deep-freezing store. Object Methods (keys, entries, assign, freeze) owns object descriptor and freeze behavior.

"use strict";
const state = Object.freeze({ count: 0 });
state.count = 2;

// ✅ Expected error:
// TypeError: Cannot assign to read only property 'count' of object '#<Object>'

A reducer must define invalid, unchanged and changed actions

function counterReducer(state, action) {
  if (!action || typeof action !== "object" || typeof action.type !== "string") {
    throw new TypeError("action with string type required");
  }
  let count = state.count, step = state.step;
  switch (action.type) {
    case "increment": count += step; break;
    case "decrement": count -= step; break;
    case "reset": count = 0; break;
    case "setStep":
      if (!Number.isInteger(action.value) || action.value < 1 || action.value > 10) {
        throw new RangeError("step must be an integer from 1 through 10");
      }
      step = action.value; break;
    default: return state;
  }
  if (count < 0 || count > 1000) throw new RangeError("count must stay from 0 through 1000");
  if (count === state.count && step === state.step) return state;
  return Object.freeze({ count: count === 0 ? 0 : count, step });
}

const start = Object.freeze({ count: 0, step: 2 });
const same = counterReducer(start, { type: "reset" });
const next = counterReducer(start, { type: "increment" });
console.log(same === start, next === start);
console.log(JSON.stringify(start), JSON.stringify(next));
try { counterReducer(start, { type: "decrement" }); }
catch (error) { console.log(error.name, error.message); }

// ✅ Expected output:
// true false
// {"count":0,"step":2} {"count":2,"step":2}
// RangeError count must stay from 0 through 1000

The reducer assumes state came from this counter model. It validates incoming actions, returns the same object for an unknown action or an unchanged result, and creates a frozen selected record for a change. Invalid known actions throw before a store commits anything. Unknown action types are ignored by explicit policy; choose a different rule if typos must be rejected.

Do not read a clock, generate IDs randomly or perform a request inside a reducer. Supply external facts through an action after validating them. The same valid state/action pair should produce the same value, making transitions replayable and tests meaningful.

Subscriptions need an explicit order and failure policy

function counterReducer(state, action) {
  if (!action || typeof action !== "object" || typeof action.type !== "string") {
    throw new TypeError("action with string type required");
  }
  let count = state.count, step = state.step;
  switch (action.type) {
    case "increment": count += step; break;
    case "decrement": count -= step; break;
    case "reset": count = 0; break;
    case "setStep":
      if (!Number.isInteger(action.value) || action.value < 1 || action.value > 10) {
        throw new RangeError("step must be an integer from 1 through 10");
      }
      step = action.value; break;
    default: return state;
  }
  if (count < 0 || count > 1000) throw new RangeError("count must stay from 0 through 1000");
  if (count === state.count && step === state.step) return state;
  return Object.freeze({ count: count === 0 ? 0 : count, step });
}

function createCounterStore(initial = { count: 0, step: 1 }) {
  if (!initial || typeof initial !== "object" ||
      !Number.isInteger(initial.count) || initial.count < 0 || initial.count > 1000 ||
      !Number.isInteger(initial.step) || initial.step < 1 || initial.step > 10) {
    throw new TypeError("valid initial counter required");
  }
  let state = Object.freeze({ count: initial.count === 0 ? 0 : initial.count, step: initial.step });
  let dispatching = false;
  const listeners = new Map();
  function subscribe(listener) {
    if (typeof listener !== "function") throw new TypeError("listener must be callable");
    const token = Symbol();
    listeners.set(token, listener);
    let active = true;
    return () => {
      if (!active) return;
      active = false; listeners.delete(token);
    };
  }
  function dispatch(action) {
    if (dispatching) throw new Error("dispatch during notification is not allowed");
    dispatching = true;
    try {
      const previous = state;
      const next = counterReducer(previous, action);
      if (next === previous) return state;
      state = next;
      const batch = [...listeners.values()];
      const failures = [];
      for (const listener of batch) {
        try { listener(state, previous); } catch (error) { failures.push(error); }
      }
      if (failures.length) throw new AggregateError(failures, "listener failures after state commit");
      return state;
    } finally { dispatching = false; }
  }
  return Object.freeze({ getState: () => state, subscribe, dispatch });
}

const store = createCounterStore();
const seen = [];
const off = store.subscribe((next, previous) => seen.push(previous.count + "->" + next.count));
store.subscribe(next => seen.push("current:" + store.getState().count));
store.dispatch({ type: "increment" });
off(); off();
store.dispatch({ type: "increment" });
console.log(seen.join(", "));
console.log(JSON.stringify(store.getState()));

// ✅ Expected output:
// 0->1, current:1, current:2
// {"count":2,"step":1}
function counterReducer(state, action) {
  if (!action || typeof action !== "object" || typeof action.type !== "string") {
    throw new TypeError("action with string type required");
  }
  let count = state.count, step = state.step;
  switch (action.type) {
    case "increment": count += step; break;
    case "decrement": count -= step; break;
    case "reset": count = 0; break;
    case "setStep":
      if (!Number.isInteger(action.value) || action.value < 1 || action.value > 10) {
        throw new RangeError("step must be an integer from 1 through 10");
      }
      step = action.value; break;
    default: return state;
  }
  if (count < 0 || count > 1000) throw new RangeError("count must stay from 0 through 1000");
  if (count === state.count && step === state.step) return state;
  return Object.freeze({ count: count === 0 ? 0 : count, step });
}

function createCounterStore(initial = { count: 0, step: 1 }) {
  if (!initial || typeof initial !== "object" ||
      !Number.isInteger(initial.count) || initial.count < 0 || initial.count > 1000 ||
      !Number.isInteger(initial.step) || initial.step < 1 || initial.step > 10) {
    throw new TypeError("valid initial counter required");
  }
  let state = Object.freeze({ count: initial.count === 0 ? 0 : initial.count, step: initial.step });
  let dispatching = false;
  const listeners = new Map();
  function subscribe(listener) {
    if (typeof listener !== "function") throw new TypeError("listener must be callable");
    const token = Symbol();
    listeners.set(token, listener);
    let active = true;
    return () => {
      if (!active) return;
      active = false; listeners.delete(token);
    };
  }
  function dispatch(action) {
    if (dispatching) throw new Error("dispatch during notification is not allowed");
    dispatching = true;
    try {
      const previous = state;
      const next = counterReducer(previous, action);
      if (next === previous) return state;
      state = next;
      const batch = [...listeners.values()];
      const failures = [];
      for (const listener of batch) {
        try { listener(state, previous); } catch (error) { failures.push(error); }
      }
      if (failures.length) throw new AggregateError(failures, "listener failures after state commit");
      return state;
    } finally { dispatching = false; }
  }
  return Object.freeze({ getState: () => state, subscribe, dispatch });
}

const store = createCounterStore();
const seen = [];
store.subscribe(() => { throw new Error("view failed"); });
store.subscribe(next => seen.push(next.count));
try { store.dispatch({ type: "increment" }); }
catch (error) { console.log(error.name, error.errors.length, error.message); }
console.log(store.getState().count, seen.join(", "));

// ✅ Expected output:
// AggregateError 1 listener failures after state commit
// 1 1
function counterReducer(state, action) {
  if (!action || typeof action !== "object" || typeof action.type !== "string") {
    throw new TypeError("action with string type required");
  }
  let count = state.count, step = state.step;
  switch (action.type) {
    case "increment": count += step; break;
    case "decrement": count -= step; break;
    case "reset": count = 0; break;
    case "setStep":
      if (!Number.isInteger(action.value) || action.value < 1 || action.value > 10) {
        throw new RangeError("step must be an integer from 1 through 10");
      }
      step = action.value; break;
    default: return state;
  }
  if (count < 0 || count > 1000) throw new RangeError("count must stay from 0 through 1000");
  if (count === state.count && step === state.step) return state;
  return Object.freeze({ count: count === 0 ? 0 : count, step });
}

function createCounterStore(initial = { count: 0, step: 1 }) {
  if (!initial || typeof initial !== "object" ||
      !Number.isInteger(initial.count) || initial.count < 0 || initial.count > 1000 ||
      !Number.isInteger(initial.step) || initial.step < 1 || initial.step > 10) {
    throw new TypeError("valid initial counter required");
  }
  let state = Object.freeze({ count: initial.count === 0 ? 0 : initial.count, step: initial.step });
  let dispatching = false;
  const listeners = new Map();
  function subscribe(listener) {
    if (typeof listener !== "function") throw new TypeError("listener must be callable");
    const token = Symbol();
    listeners.set(token, listener);
    let active = true;
    return () => {
      if (!active) return;
      active = false; listeners.delete(token);
    };
  }
  function dispatch(action) {
    if (dispatching) throw new Error("dispatch during notification is not allowed");
    dispatching = true;
    try {
      const previous = state;
      const next = counterReducer(previous, action);
      if (next === previous) return state;
      state = next;
      const batch = [...listeners.values()];
      const failures = [];
      for (const listener of batch) {
        try { listener(state, previous); } catch (error) { failures.push(error); }
      }
      if (failures.length) throw new AggregateError(failures, "listener failures after state commit");
      return state;
    } finally { dispatching = false; }
  }
  return Object.freeze({ getState: () => state, subscribe, dispatch });
}

const store = createCounterStore();
const seen = [];
let added = false;
let offSecond;
store.subscribe(() => {
  seen.push("first");
  offSecond();
  if (!added) { added = true; store.subscribe(() => seen.push("new")); }
});
offSecond = store.subscribe(() => seen.push("second"));
store.dispatch({ type: "increment" });
store.dispatch({ type: "increment" });
console.log(seen.join(", "));

// ✅ Expected output:
// first, second, first, new

This store snapshots listeners once for each changed state. A listener removed during that batch still receives the current notification; a newly added listener begins with a later change. Every subscribe call creates an independent registration, including repeated use of the same function. The returned unsubscribe function is idempotent. Subscription does not invoke the listener immediately: initialize a view from getState, then subscribe.

function counterReducer(state, action) {
  if (!action || typeof action !== "object" || typeof action.type !== "string") {
    throw new TypeError("action with string type required");
  }
  let count = state.count, step = state.step;
  switch (action.type) {
    case "increment": count += step; break;
    case "decrement": count -= step; break;
    case "reset": count = 0; break;
    case "setStep":
      if (!Number.isInteger(action.value) || action.value < 1 || action.value > 10) {
        throw new RangeError("step must be an integer from 1 through 10");
      }
      step = action.value; break;
    default: return state;
  }
  if (count < 0 || count > 1000) throw new RangeError("count must stay from 0 through 1000");
  if (count === state.count && step === state.step) return state;
  return Object.freeze({ count: count === 0 ? 0 : count, step });
}

function createCounterStore(initial = { count: 0, step: 1 }) {
  if (!initial || typeof initial !== "object" ||
      !Number.isInteger(initial.count) || initial.count < 0 || initial.count > 1000 ||
      !Number.isInteger(initial.step) || initial.step < 1 || initial.step > 10) {
    throw new TypeError("valid initial counter required");
  }
  let state = Object.freeze({ count: initial.count === 0 ? 0 : initial.count, step: initial.step });
  let dispatching = false;
  const listeners = new Map();
  function subscribe(listener) {
    if (typeof listener !== "function") throw new TypeError("listener must be callable");
    const token = Symbol();
    listeners.set(token, listener);
    let active = true;
    return () => {
      if (!active) return;
      active = false; listeners.delete(token);
    };
  }
  function dispatch(action) {
    if (dispatching) throw new Error("dispatch during notification is not allowed");
    dispatching = true;
    try {
      const previous = state;
      const next = counterReducer(previous, action);
      if (next === previous) return state;
      state = next;
      const batch = [...listeners.values()];
      const failures = [];
      for (const listener of batch) {
        try { listener(state, previous); } catch (error) { failures.push(error); }
      }
      if (failures.length) throw new AggregateError(failures, "listener failures after state commit");
      return state;
    } finally { dispatching = false; }
  }
  return Object.freeze({ getState: () => state, subscribe, dispatch });
}

const store = createCounterStore();
const off = store.subscribe(() => store.dispatch({ type: "increment" }));
try { store.dispatch({ type: "increment" }); }
catch (error) { console.log(error.name, error.errors[0].message); }
console.log(store.getState().count);
off();
store.dispatch({ type: "increment" });
console.log(store.getState().count);

// ✅ Expected output:
// AggregateError dispatch during notification is not allowed
// 1
// 2

The guard prevents a subscriber from recursively dispatching during notification. Its error is collected with other listener failures after the already-committed transition. The finally block releases the guard even when a reducer or listener fails. This policy avoids hidden queue ordering; it does not claim to reproduce Redux or another library’s full semantics.

Guided exercise: change one field without losing the others

Fill the literal hints and inspect both the value and the reference. Do not mutate the previous state.

const previous = Object.freeze({ count: 4, step: 2 });
const next = Object.___({ count: previous.count + previous.___, step: previous.step }); // 👉 replace ___ with freeze
// 👉 replace ___ with step
console.log(next.count, previous.count);
console.log(next === ___); // 👉 replace ___ with previous

// ✅ Expected output:
// 6 4
// false

Build brief: a bounded counter store with reliable notification semantics

Implement counterReducer and createCounterStore. Initial count must be an integer in 0–1000 and step an integer in 1–10. Select and freeze only those fields; normalize a zero count to positive zero. Actions increment, decrement, reset and setStep must keep the state within those bounds. reset changes only count. Unknown string action types return the same state. Invalid actions must leave the current state unchanged.

Expose a frozen handle with getState, subscribe and dispatch. Repeated reads return the same frozen state until a real change. Notify a snapshot of independently registered listeners in registration order, passing next and previous states. Continue after listener errors and then throw AggregateError; the new state stays committed. No-op actions do not notify. Reject reentrant dispatch and always release the dispatch guard.

function counterReducer(state, action) {
  if (!action || typeof action !== "object" || typeof action.type !== "string") {
    throw new TypeError("action with string type required");
  }
  let count = state.count, step = state.step;
  switch (action.type) {
    case "increment": count += step; break;
    case "decrement": count -= step; break;
    case "reset": count = 0; break;
    case "setStep":
      if (!Number.isInteger(action.value) || action.value < 1 || action.value > 10) {
        throw new RangeError("step must be an integer from 1 through 10");
      }
      step = action.value; break;
    default: return state;
  }
  if (count < 0 || count > 1000) throw new RangeError("count must stay from 0 through 1000");
  if (count === state.count && step === state.step) return state;
  return Object.freeze({ count: count === 0 ? 0 : count, step });
}

function createCounterStore(initial = { count: 0, step: 1 }) {
  if (!initial || typeof initial !== "object" ||
      !Number.isInteger(initial.count) || initial.count < 0 || initial.count > 1000 ||
      !Number.isInteger(initial.step) || initial.step < 1 || initial.step > 10) {
    throw new TypeError("valid initial counter required");
  }
  let state = Object.freeze({ count: initial.count === 0 ? 0 : initial.count, step: initial.step });
  let dispatching = false;
  const listeners = new Map();
  function subscribe(listener) {
    if (typeof listener !== "function") throw new TypeError("listener must be callable");
    const token = Symbol();
    listeners.set(token, listener);
    let active = true;
    return () => {
      if (!active) return;
      active = false; listeners.delete(token);
    };
  }
  function dispatch(action) {
    if (dispatching) throw new Error("dispatch during notification is not allowed");
    dispatching = true;
    try {
      const previous = state;
      const next = counterReducer(previous, action);
      if (next === previous) return state;
      state = next;
      const batch = [...listeners.values()];
      const failures = [];
      for (const listener of batch) {
        try { listener(state, previous); } catch (error) { failures.push(error); }
      }
      if (failures.length) throw new AggregateError(failures, "listener failures after state commit");
      return state;
    } finally { dispatching = false; }
  }
  return Object.freeze({ getState: () => state, subscribe, dispatch });
}

const initial = { count: 3, step: 2, ignored: "not state" };
const store = createCounterStore(initial);
initial.count = 999;
const start = store.getState();
const seen = [];
const listener = next => seen.push(next.count);
const firstOff = store.subscribe(listener);
const secondOff = store.subscribe(listener);
store.dispatch({ type: "unknown" });
console.log(store.getState() === start, seen.length);
store.dispatch({ type: "increment" });
firstOff();
store.dispatch({ type: "setStep", value: 3 });
secondOff();
store.dispatch({ type: "decrement" });
console.log(seen.join(", "));
console.log(JSON.stringify(store.getState()), Object.isFrozen(store.getState()));
try { store.dispatch({ type: "setStep", value: 0 }); }
catch (error) { console.log(error.name); }
console.log(JSON.stringify(store.getState()));

// ✅ Expected output:
// true 0
// 5, 5, 5
// {"count":2,"step":3} true
// RangeError
// {"count":2,"step":3}

Test both numeric boundaries, every no-op, invalid initial data, invalid actions, duplicate subscriptions, removal/addition during notification, listener exceptions and nested dispatch. Also verify that the store remains usable after each failure. This flat model does not supply undo history, time travel, cross-tab synchronization, persistence or a framework binding.

An effect can resolve after newer state is selected. Use a request identity or cancellation policy at the effect boundary before dispatching its result; AbortController & Cancelling Async Work and Checkpoint: Browser APIs own that asynchronous lifetime.

Practice quiz

What does this complete program print? const s={items:[{done:false}]};const n={...s};n.items[0].done=true;console.log(s.items[0].done);

  • true
  • false
  • undefined
  • TypeError

Answer: true. A shallow object copy retains the nested array and record references.

What does this complete program print? function counterReducer(state, action) { if (!action || typeof action !== "object" || typeof action.type !== "string") { throw new TypeError("action with string type required"); } let count = state.count, step = state.step; switch (action.type) { case "increment": count += step; break; case "decrement": count -= step; break; case "reset": count = 0; break; case "setStep": if (!Number.isInteger(action.value) || action.value < 1 || action.value > 10) { throw new RangeError("step must be an integer from 1 through 10"); } step = action.value; break; default: return state; } if (count < 0 || count > 1000) throw new RangeError("count must stay from 0 through 1000"); if (count === state.count && step === state.step) return state; return Object.freeze({ count: count === 0 ? 0 : count, step }); } const s=Object.freeze({count:0,step:1});console.log(counterReducer(s,{type:"reset"})===s);

  • false
  • true
  • undefined
  • RangeError

Answer: true. An unchanged reset returns the original reference.

When does this store commit a changed state?

  • After every listener succeeds
  • Only after saving to a server
  • Before notifying the snapshot of listeners
  • Only on the next browser frame

Answer: Before notifying the snapshot of listeners. Listeners see the committed state; failures do not roll it back.

A listener unsubscribes another listener in the current snapshot. What happens here?

  • The current notification is canceled
  • All listeners are removed
  • Dispatch rolls back
  • The removed listener still runs in this batch but not later ones

Answer: The removed listener still runs in this batch but not later ones. The batch policy is explicit and stable.

What does this complete program print? const s=Object.freeze({count:2,step:3});console.log(s.count*s.step);

  • 6
  • 2
  • 3
  • 23

Answer: 6. A derived value need not be stored as a second authoritative field.

Why is shallow freezing sufficient for this counter state?

  • freeze recursively protects every JavaScript value
  • The selected state contains only numeric fields
  • Listeners cannot ever throw
  • The state is stored in JSON

Answer: The selected state contains only numeric fields. The model is flat; this does not establish a generic deep-freeze guarantee.

What does this complete program print? function counterReducer(state, action) { if (!action || typeof action !== "object" || typeof action.type !== "string") { throw new TypeError("action with string type required"); } let count = state.count, step = state.step; switch (action.type) { case "increment": count += step; break; case "decrement": count -= step; break; case "reset": count = 0; break; case "setStep": if (!Number.isInteger(action.value) || action.value < 1 || action.value > 10) { throw new RangeError("step must be an integer from 1 through 10"); } step = action.value; break; default: return state; } if (count < 0 || count > 1000) throw new RangeError("count must stay from 0 through 1000"); if (count === state.count && step === state.step) return state; return Object.freeze({ count: count === 0 ? 0 : count, step }); } function createCounterStore(initial = { count: 0, step: 1 }) { if (!initial || typeof initial !== "object" || !Number.isInteger(initial.count) || initial.count < 0 || initial.count > 1000 || !Number.isInteger(initial.step) || initial.step < 1 || initial.step > 10) { throw new TypeError("valid initial counter required"); } let state = Object.freeze({ count: initial.count === 0 ? 0 : initial.count, step: initial.step }); let dispatching = false; const listeners = new Map(); function subscribe(listener) { if (typeof listener !== "function") throw new TypeError("listener must be callable"); const token = Symbol(); listeners.set(token, listener); let active = true; return () => { if (!active) return; active = false; listeners.delete(token); }; } function dispatch(action) { if (dispatching) throw new Error("dispatch during notification is not allowed"); dispatching = true; try { const previous = state; const next = counterReducer(previous, action); if (next === previous) return state; state = next; const batch = [...listeners.values()]; const failures = []; for (const listener of batch) { try { listener(state, previous); } catch (error) { failures.push(error); } } if (failures.length) throw new AggregateError(failures, "listener failures after state commit"); return state; } finally { dispatching = false; } } return Object.freeze({ getState: () => state, subscribe, dispatch }); } const s=createCounterStore();let n=0;s.subscribe(()=>n++);s.dispatch({type:"unknown"});console.log(n);

  • 1
  • 2
  • 0
  • undefined

Answer: 0. No-op identity prevents a notification.

What should happen if an asynchronous request finishes after it becomes obsolete?

  • Always overwrite the latest state
  • Move the request into the reducer
  • Disable validation
  • Apply the effect’s identity/cancellation policy before dispatching its result

Answer: Apply the effect’s identity/cancellation policy before dispatching its result. The reducer cannot infer whether an external response is still current.

Continue this course

Related lessons