Skip to main content

Frontend development · Intermediate · 25 min

Manage app state in plain JavaScript with a store and events

By Padding · Updated 18 Nov 2026
Modern browsers · DOM EventTarget and Web Storage APIs · checked in Chromium 159 · Node.js 26.13

You will build a shopping list app with no framework, where one state object, a small store built on EventTarget and a render function keep the screen and the data in step, with derived counts and a list that survives a reload.

On this page

Most bugs in a hand-written interface come from the same place: the data says one thing and the screen says another. A click handler updates an array and forgets a label, or updates a label and forgets the array. Frameworks such as React, Vue and Svelte exist largely to make that class of bug hard to write. The idea underneath them is small enough to build yourself in about 60 lines, and building it once makes every framework's state model easier to learn.

In this tutorial you build a shopping list with no library at all. You start with the usual approach, watch it go out of step, then rebuild it around four pieces:

  • one state object that holds everything the screen shows
  • update functions that take the old state and return a new one, without changing the old one
  • a store built on the browser's EventTarget, which holds the current state and tells subscribers when it changes
  • a render function that redraws the screen from state, so the screen can only ever show what the data says

Then you keep counts computed rather than stored, save the list to localStorage and prove the whole thing with a browser test. The finished app is a few kilobytes of your own code with nothing else to download, which suits a low-end Android phone on prepaid data.

Step 1 · Set up the page and a local server

Browsers refuse to load JavaScript modules from a page opened straight from disk with file://, so serve the page over HTTP from the start. Make a demo folder with the page, an empty script and a package.json that tells Node.js the .js files here are modules:

Bash
mkdir -p ~/shopping-list-demo
cd ~/shopping-list-demo
cat > package.json <<'JSON'
{
  "name": "shopping-list-demo",
  "private": true,
  "type": "module"
}
JSON
cat > index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Shopping list</title>
  <style>
    body { margin: 0; font-family: system-ui, sans-serif; line-height: 1.5; background: #f6f7f8; color: #1b1f24; }
    main { max-width: 28rem; margin: 0 auto; padding: 1rem; }
    form { display: flex; gap: 0.5rem; align-items: end; flex-wrap: wrap; }
    form label { flex-basis: 100%; font-weight: 600; }
    input[type="text"] { flex: 1; min-width: 0; min-height: 2.75rem; padding: 0 0.75rem; font: inherit; }
    button { min-height: 2.75rem; padding: 0 1rem; font: inherit; }
    ul { list-style: none; padding: 0; }
    li label { display: flex; gap: 0.5rem; align-items: center; min-height: 2.75rem; }
    li input { width: 1.25rem; height: 1.25rem; }
    li:has(input:checked) { color: #5a6270; text-decoration: line-through; }
  </style>
</head>
<body>
  <main>
    <h1>Shopping list</h1>
    <form id="add">
      <label for="item">Item</label>
      <input type="text" id="item" name="item" autocomplete="off" required>
      <button type="submit">Add</button>
    </form>
    <p id="count" role="status"></p>
    <ul id="list"></ul>
    <button type="button" id="clear">Clear bought</button>
  </main>
  <script type="module" src="app.js"></script>
</body>
</html>
HTML
touch app.js

role="status" on the count makes it a polite live region, so a screen reader announces the new count after each change without moving focus.

Now a server. Node.js has no built-in static file server, so write a small one that serves only the page's own .html and .js files:

Bash
cd ~/shopping-list-demo
cat > server.mjs <<'JS'
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { extname, join } from 'node:path';

const types = {
  '.html': 'text/html; charset=utf-8',
  '.js': 'text/javascript; charset=utf-8',
};

export function start(port = 8080) {
  const server = createServer(async (req, res) => {
    const path = new URL(req.url, 'http://localhost').pathname;
    const file = path === '/' ? 'index.html' : path.slice(1);
    if (!types[extname(file)] || file.includes('/')) {
      res.writeHead(404).end('Not found');
      return;
    }
    try {
      const body = await readFile(join(import.meta.dirname, file));
      res.writeHead(200, { 'content-type': types[extname(file)] }).end(body);
    } catch {
      res.writeHead(404).end('Not found');
    }
  });
  return new Promise((resolve) => server.listen(port, '127.0.0.1', () => resolve(server)));
}

if (import.meta.main) {
  await start();
  console.log('Open http://127.0.0.1:8080');
}
JS
node --check server.mjs

start() is exported so the browser test at the end can run the same server on a free port, and import.meta.main is true only when you run the file directly. Start it in its own terminal window and leave it running:

Bash
cd ~/shopping-list-demo
node server.mjs

Check it worked

The terminal prints Open http://127.0.0.1:8080. Open that address. You see the Shopping list heading, an Item box with an Add button and a Clear bought button. Type Rice and press Enter: the page reloads with ?item=Rice in the address bar and nothing is added, because no script handles the form yet.

Step 2 · See the screen and the data disagree

Start with the way most people first write this: keep an array, and in each handler change the array and the bit of the page that handler is thinking about.

Bash
cd ~/shopping-list-demo
cat > app.js <<'JS'
let items = [];
const form = document.querySelector('#add');
const list = document.querySelector('#list');
const count = document.querySelector('#count');

function updateCount() {
  const left = items.filter((item) => !item.bought).length;
  count.textContent = `${left} left`;
}

form.addEventListener('submit', (event) => {
  event.preventDefault();
  const name = form.elements.namedItem('item').value.trim();
  if (!name) return;
  const item = { name, bought: false };
  items.push(item);

  const box = document.createElement('input');
  box.type = 'checkbox';
  box.addEventListener('change', () => {
    item.bought = box.checked;
    updateCount();
  });
  const label = document.createElement('label');
  label.append(box, ' ', name);
  const li = document.createElement('li');
  li.append(label);
  list.append(li);

  form.reset();
  updateCount();
});

document.querySelector('#clear').addEventListener('click', () => {
  items = items.filter((item) => !item.bought);
  updateCount();
});
JS
node --check app.js

Every handler looks reasonable on its own. The Clear bought handler removes the bought items from the array and updates the count, but nothing removes their rows from the page. Nothing errors; the screen quietly stops telling the truth.

Check it worked

Reload the page. Add Rice and Beans, tick Rice, then click Clear bought. The count says 1 left, yet Rice is still on the list, ticked. Untick Rice: the count still says 1 left while two unticked items are on screen, because the Rice object the checkbox changes is no longer in the array. Every new handler you add to this version is one more place to forget a piece of the page.

Step 3 · Put all state in one object with update functions

The fix starts by giving the data one home. Everything the screen shows comes from one object: the items, and the next id to hand out. Each change is a function that takes the current state and returns a new state. It never edits the old one.

Bash
cd ~/shopping-list-demo
cat > state.js <<'JS'
export const initialState = Object.freeze({ items: Object.freeze([]), nextId: 1 });

export function addItem(state, name) {
  const clean = name.trim();
  if (!clean) return state;
  return {
    ...state,
    items: [...state.items, { id: state.nextId, name: clean, bought: false }],
    nextId: state.nextId + 1,
  };
}

export function toggleItem(state, id) {
  return {
    ...state,
    items: state.items.map((item) => (item.id === id ? { ...item, bought: !item.bought } : item)),
  };
}

export function clearBought(state) {
  return { ...state, items: state.items.filter((item) => !item.bought) };
}
JS

Three habits in that file matter:

  • Spread, map and filter instead of push, splice or assignment. [...state.items, newItem] builds a new array. toggleItem copies only the item that changes; the others are reused as they are.
  • Return the same object when nothing changes. addItem with a blank name returns state itself. The store in the next step uses that to skip work.
  • Ids come from state, not from Math.random() or the clock. With the same state and the same arguments, an update function always gives the same result, which makes it easy to check without a browser.

Replacing instead of mutating means the store can tell whether anything changed with a single === comparison, rather than walking every item. It is the same rule React applies to useState.

Check the functions in Node.js. deepFreeze makes any attempt to change an old state throw an error, because modules run in strict mode:

Bash
cd ~/shopping-list-demo
cat > check-state.js <<'JS'
import assert from 'node:assert/strict';
import { initialState, addItem, toggleItem, clearBought } from './state.js';

const deepFreeze = (value) => {
  if (value && typeof value === 'object') {
    Object.values(value).forEach(deepFreeze);
    Object.freeze(value);
  }
  return value;
};

const one = deepFreeze(addItem(initialState, '  Rice '));
const two = deepFreeze(addItem(one, 'Beans'));
const ticked = deepFreeze(toggleItem(two, 1));
const cleared = clearBought(ticked);

assert.deepEqual(one.items, [{ id: 1, name: 'Rice', bought: false }]);
assert.equal(two.items[0].bought, false, 'the old state is untouched');
assert.equal(ticked.items[0].bought, true);
assert.equal(ticked.items[1], two.items[1], 'unchanged items are reused');
assert.deepEqual(cleared.items.map((item) => item.name), ['Beans']);
assert.equal(addItem(two, '   '), two, 'no change returns the same object');
console.log('PASS: update functions return new state and leave the old one alone');
JS
node check-state.js

Check it worked

The output ends with PASS: update functions return new state and leave the old one alone. To see the freeze working, change items: [...state.items, ...] in addItem to items: (state.items.push({ id: state.nextId, name: clean, bought: false }), state.items) and run node check-state.js again: it stops with TypeError: Cannot add property 0, object is not extensible. Put the line back.

Step 4 · Build a store on EventTarget

The state needs a holder that other code can read and listen to. The browser already has a listener system, EventTarget, the same one behind addEventListener on buttons. You can create one on its own with new EventTarget(), so the store needs no event code of its own:

Bash
cd ~/shopping-list-demo
cat > store.js <<'JS'
export function createStore(initialState) {
  let state = initialState;
  const events = new EventTarget();

  return {
    getState() {
      return state;
    },
    update(change, ...args) {
      const next = change(state, ...args);
      if (next === state) return;
      state = next;
      events.dispatchEvent(new CustomEvent('change', { detail: state }));
    },
    subscribe(listener) {
      const handler = (event) => listener(event.detail);
      events.addEventListener('change', handler);
      return () => events.removeEventListener('change', handler);
    },
  };
}
JS

update takes one of the functions from state.js and its arguments, so the store never needs to know what a shopping list is. let state is private to the function: the only way to change it is through update, which is what makes every change visible to subscribers. dispatchEvent calls every listener straight away, before update returns, so code after an update always sees subscribers already run. If one listener throws, the browser reports the error and still calls the others.

subscribe returns a function that removes the listener. Keep it if a part of the page can go away, and call it then, so a removed view stops redrawing.

Node.js has EventTarget and CustomEvent built in too, so check the store there:

Bash
cd ~/shopping-list-demo
cat > check-store.js <<'JS'
import assert from 'node:assert/strict';
import { createStore } from './store.js';
import { initialState, addItem, toggleItem } from './state.js';

const store = createStore(initialState);
const seen = [];
const stop = store.subscribe((state) => seen.push(state.items.length));

store.update(addItem, 'Rice');
store.update(addItem, '   ');
store.update(toggleItem, 1);
assert.deepEqual(seen, [1, 1], 'one notice per real change, none for a blank name');

stop();
store.update(addItem, 'Beans');
assert.equal(seen.length, 2, 'no notice after unsubscribing');
assert.equal(store.getState().items.length, 2);
console.log('PASS: the store notifies subscribers once per change');
JS
node check-store.js

Check it worked

The output ends with PASS: the store notifies subscribers once per change. The blank name produced no notice because addItem returned the same object and the store compared it with ===.

Step 5 · Redraw the screen from state

Now the rule that removes the bug: event handlers never touch the page. They only call store.update. One render function draws the list from whatever the state is, and the store calls it after every change.

Write the view:

Bash
cd ~/shopping-list-demo
cat > view.js <<'JS'
const list = document.querySelector('#list');

function itemRow(item) {
  const box = document.createElement('input');
  box.type = 'checkbox';
  box.checked = item.bought;
  box.dataset.id = item.id;
  const label = document.createElement('label');
  label.append(box, ' ', item.name);
  const li = document.createElement('li');
  li.append(label);
  return li;
}

export function render(state) {
  const focusedId = document.activeElement?.dataset.id;
  list.replaceChildren(...state.items.map(itemRow));
  if (focusedId) list.querySelector(`[data-id="${focusedId}"]`)?.focus();
}
JS
node --check view.js

Then replace the old app.js with a version that only wires events to updates:

Bash
cd ~/shopping-list-demo
cat > app.js <<'JS'
import { createStore } from './store.js';
import { initialState, addItem, toggleItem, clearBought } from './state.js';
import { render } from './view.js';

const store = createStore(initialState);
const form = document.querySelector('#add');

form.addEventListener('submit', (event) => {
  event.preventDefault();
  store.update(addItem, form.elements.namedItem('item').value);
  form.reset();
});

document.querySelector('#list').addEventListener('change', (event) => {
  store.update(toggleItem, Number(event.target.dataset.id));
});

document.querySelector('#clear').addEventListener('click', () => {
  store.update(clearBought);
});

store.subscribe(render);
render(store.getState());
JS
node --check app.js

Some details worth knowing:

  • replaceChildren throws the old rows away and builds new ones. For a shopping list that costs nothing you can notice, even on a slow phone. For a list of thousands of rows it would, and keeping the rows that did not change is a large part of what a framework's renderer does.
  • Focus is put back by hand. Replacing a checkbox the reader just toggled with the keyboard would drop their focus back to the top of the page. render notes the focused item's id first and focuses the new checkbox with that id afterwards. Frameworks do this for you by reusing the element.
  • namedItem('item'), not elements.item. A form's elements collection has its own item() method, so form.elements.item gives you that method instead of the input called item. namedItem always looks the field up by name.
  • One listener on the list handles every checkbox. The change event bubbles up from each checkbox, so rows created later need no listeners of their own.
  • Names go in as text. label.append(..., item.name) adds a text node. An item called <b>Tomatoes</b> shows those characters rather than bold text, so nobody can inject markup through the list. Building rows with innerHTML and a template string would not be safe.

Check it worked

Reload the page and repeat the test from earlier: add Rice and Beans, tick Rice and click Clear bought. Rice disappears from the list. Click in the Item box, press Tab until a checkbox is focused and press Space: it ticks and keeps its focus ring, even though the row was redrawn.

Step 6 · Compute derived values instead of storing them

The page still needs the count, and Clear bought should be disabled when nothing is ticked. It is tempting to add left: 2 to the state and keep it updated. That brings back the step 2 bug in a new form: every update function would have to remember to adjust it, and one that forgets leaves the count wrong. Anything you can work out from the state should be worked out from it each time.

Add two small functions, often called selectors, to the end of state.js:

Bash
cd ~/shopping-list-demo
cat >> state.js <<'JS'

export function itemsLeft(state) {
  return state.items.filter((item) => !item.bought).length;
}

export function hasBought(state) {
  return state.items.some((item) => item.bought);
}
JS

Then give the view the summary and the button state. Replace view.js:

Bash
cd ~/shopping-list-demo
cat > view.js <<'JS'
import { itemsLeft, hasBought } from './state.js';

const list = document.querySelector('#list');
const count = document.querySelector('#count');
const clear = document.querySelector('#clear');

function itemRow(item) {
  const box = document.createElement('input');
  box.type = 'checkbox';
  box.checked = item.bought;
  box.dataset.id = item.id;
  const label = document.createElement('label');
  label.append(box, ' ', item.name);
  const li = document.createElement('li');
  li.append(label);
  return li;
}

function summary(state) {
  if (state.items.length === 0) return 'Your list is empty';
  const left = itemsLeft(state);
  if (left === 0) return 'Nothing left to buy';
  return `${left} ${left === 1 ? 'item' : 'items'} left`;
}

export function render(state) {
  const focusedId = document.activeElement?.dataset.id;
  list.replaceChildren(...state.items.map(itemRow));
  if (focusedId) list.querySelector(`[data-id="${focusedId}"]`)?.focus();
  count.textContent = summary(state);
  clear.disabled = !hasBought(state);
}
JS
node --check view.js

Filtering a short list on every render is cheap. If a derived value ever becomes slow to compute, cache it against the state object it came from; because states are replaced and never edited, the same object always gives the same answer.

The item or items choice only works in English. If the app is translated, into French, Swahili or Yoruba for example, use Intl.PluralRules and a message per plural form instead of this test.

Check it worked

Reload the page. Before you add anything it says Your list is empty and Clear bought is greyed out. Add three items: 3 items left. Tick one: 2 items left, and Clear bought becomes clickable. Tick the other two: Nothing left to buy.

Step 7 · Save the store to localStorage

A shopping list that empties on reload is not much use in a shop with a weak signal. Saving is one more subscriber: whenever the state changes, write it to localStorage. Loading is reading it back once, before the store is created.

Saved data is user input: it may be missing, broken or left over from an older version of your app. Reading localStorage can also throw when the browser blocks storage. Guard both directions:

Bash
cd ~/shopping-list-demo
cat > persist.js <<'JS'
const KEY = 'shopping-list.v1';

function isValid(saved) {
  return (
    saved !== null &&
    typeof saved === 'object' &&
    Number.isInteger(saved.nextId) &&
    Array.isArray(saved.items) &&
    saved.items.every(
      (item) =>
        Number.isInteger(item?.id) &&
        item.id < saved.nextId &&
        typeof item.name === 'string' &&
        typeof item.bought === 'boolean',
    )
  );
}

export function loadState(fallback) {
  try {
    const saved = JSON.parse(localStorage.getItem(KEY));
    if (isValid(saved)) return saved;
  } catch {
    // Broken JSON or blocked storage: start from the fallback.
  }
  return fallback;
}

export function saveState(state) {
  try {
    localStorage.setItem(KEY, JSON.stringify(state));
  } catch {
    // Storage full or blocked: the list still works for this visit.
  }
}
JS
cat > app.js <<'JS'
import { createStore } from './store.js';
import { initialState, addItem, toggleItem, clearBought } from './state.js';
import { render } from './view.js';
import { loadState, saveState } from './persist.js';

const store = createStore(loadState(initialState));
const form = document.querySelector('#add');

form.addEventListener('submit', (event) => {
  event.preventDefault();
  store.update(addItem, form.elements.namedItem('item').value);
  form.reset();
});

document.querySelector('#list').addEventListener('change', (event) => {
  store.update(toggleItem, Number(event.target.dataset.id));
});

document.querySelector('#clear').addEventListener('click', () => {
  store.update(clearBought);
});

store.subscribe(render);
store.subscribe(saveState);
render(store.getState());
JS
node --check persist.js
node --check app.js

The only change to app.js is two lines: the store starts from loadState(initialState) and saveState subscribes beside render. Neither the update functions nor the view know that saving exists. item.id < saved.nextId rejects saved data whose ids could clash with the next new item. The .v1 in the key leaves room to change the shape later; remember user settings with localStorage covers upgrading old keys and syncing between tabs.

Check it worked

Reload, add Garri and Tomatoes, tick Garri and reload again. Both items are still there and Garri is still ticked. In the browser's DevTools console, run localStorage.getItem('shopping-list.v1') to see the saved JSON. Then run localStorage.setItem('shopping-list.v1', '{"items": oops') and reload: the page starts with an empty list and the console shows no error.

Step 8 · Test the app in a real browser

Clicking through once proves it once. A test proves the screen and the data agree after every future change. Install Playwright, which drives a real browser from a script. --with-deps also installs the system libraries Chromium needs on Linux and can ask for your password:

Bash
cd ~/shopping-list-demo
npm install playwright@1.65.1
npx playwright install --with-deps chromium

The test compares what the page shows with what was saved, which is the bug from step 2 turned into an assertion:

Bash
cd ~/shopping-list-demo
cat > test-list.mjs <<'JS'
import { chromium } from 'playwright';
import assert from 'node:assert/strict';
import { start } from './server.mjs';

const server = await start(0);
const url = `http://127.0.0.1:${server.address().port}/`;
const browser = await chromium.launch();
const shown = async (page) => (await page.locator('#list label').allInnerTexts()).map((t) => t.trim());
const saved = (page) => page.evaluate(() => JSON.parse(localStorage.getItem('shopping-list.v1')));

try {
  const page = await browser.newPage({ viewport: { width: 390, height: 844 } });
  const errors = [];
  page.on('pageerror', (e) => errors.push(e.message));
  await page.goto(url);

  const status = page.getByRole('status');
  const clear = page.getByRole('button', { name: 'Clear bought' });
  const add = async (name) => {
    await page.getByLabel('Item', { exact: true }).fill(name);
    await page.getByRole('button', { name: 'Add' }).click();
  };

  assert.equal(await status.textContent(), 'Your list is empty');
  assert.ok(await clear.isDisabled());

  // Adding items, including non-English text and text that looks like HTML.
  for (const name of ['Rice', 'Ẹ̀wà (beans)', '<b>Tomatoes</b>', '   ']) await add(name);
  assert.deepEqual(await shown(page), ['Rice', 'Ẹ̀wà (beans)', '<b>Tomatoes</b>']);
  assert.equal(await page.locator('#list b').count(), 0, 'names are text, not markup');
  assert.equal(await status.textContent(), '3 items left');

  // Ticking with the keyboard keeps focus on the same item after the redraw.
  const rice = page.getByRole('checkbox', { name: 'Rice' });
  await rice.focus();
  await page.keyboard.press('Space');
  assert.ok(await rice.isChecked());
  assert.equal(await page.evaluate(() => document.activeElement.dataset.id), '1');
  assert.equal(await status.textContent(), '2 items left');
  assert.ok(await clear.isEnabled());

  // Clear bought: the screen and the saved data agree.
  await clear.click();
  assert.deepEqual(await shown(page), ['Ẹ̀wà (beans)', '<b>Tomatoes</b>']);
  assert.deepEqual((await saved(page)).items.map((item) => item.name), await shown(page));
  assert.ok(await clear.isDisabled());

  // The list survives a reload, and new items get fresh ids.
  await page.reload();
  assert.deepEqual(await shown(page), ['Ẹ̀wà (beans)', '<b>Tomatoes</b>']);
  assert.equal(await status.textContent(), '2 items left');
  await add('Garri');
  const ids = await page.locator('#list input').evaluateAll((els) => els.map((el) => el.dataset.id));
  assert.equal(new Set(ids).size, 3, 'ids are unique');
  for (const box of await page.getByRole('checkbox').all()) await box.check();
  assert.equal(await status.textContent(), 'Nothing left to buy');

  // Broken saved data falls back to an empty list without errors.
  await page.evaluate(() => localStorage.setItem('shopping-list.v1', '{"items": oops'));
  await page.reload();
  assert.equal(await status.textContent(), 'Your list is empty');
  assert.deepEqual(errors, [], 'no uncaught errors');

  // No sideways scrolling on a phone-sized screen.
  const overflow = await page.evaluate(() => document.documentElement.scrollWidth > document.documentElement.clientWidth);
  assert.equal(overflow, false);
} finally {
  await browser.close();
  server.close();
}
console.log('PASS: screen, store and saved list agree');
JS
node test-list.mjs

The test finds elements by role and label, the same names a screen reader uses, so renaming a label without updating the page breaks the test as well.

Check it worked

The last line of output is PASS: screen, store and saved list agree. To see it fail for the right reason, delete the line store.subscribe(render); from app.js and run node test-list.mjs again: it stops with an AssertionError on the list contents and no PASS line, because the data changes and the screen does not. Put the line back and the test passes again.

Step 9 · Clean up

The saved list lives in your browser, not in the demo folder. On the Shopping list tab, run localStorage.removeItem('shopping-list.v1') in the DevTools console. Then stop the server with Ctrl+C in its terminal and remove the folder, which also removes the local Playwright install:

Bash
cd ~
rm -rf ~/shopping-list-demo

The browser Playwright downloaded stays in its shared cache; npx playwright uninstall removes it if you no longer need it.

Check it worked

ls ~/shopping-list-demo reports that there is no such file or directory, and http://127.0.0.1:8080 no longer loads.

Next steps

You now have the shape every front-end framework shares: state in one place, changes that produce new state, a notice when it changes and a view drawn from it. What a framework adds is mostly the parts you did by hand. React's useState holds the state per component and re-renders when you set a new value, skipping the work when the new value is identical by Object.is, which is why it asks you to replace objects rather than mutate them. Svelte 5's $state wraps arrays and objects in proxies, so there you can push to an array and it still redraws. Both keep unchanged elements and focus for you instead of rebuilding every row.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Digital Transformation

Get new tutorials

New tutorials, about twice a month.