JomMula

Frontend Development: HTML to React · JavaScript · Lesson 18

State and localStorage: remember it

The food log needs to remember what you added — even after a refresh. Learn state, a render function, and localStorage: the same idea React will build on.

8 min readJavaScriptstatelocalStorageUpdated October 2026

The calculator can calculate. But if you add a food and refresh the page, it’s gone. Real apps remember.

There are two ideas in this lesson:

  1. State — the data that changes while the app is running.
  2. Persistence — storing that data somewhere so it survives a refresh.

They’re related, but they’re not the same thing.

State is the source of truth

For our food log, the state is simple:

let foods = [
  { id: 1, name: "Oatmeal", calories: 320 },
  { id: 2, name: "Chicken and rice", calories: 550 },
];

Everything else is derived from it:

  • The list of rows in the table.
  • The total calories.
  • The “remaining” number.

Don’t store the total as a separate variable that you have to keep in sync. Calculate it from foods whenever you render. One source of truth.

Render from state

A render function takes the current state and updates the page to match:

function render() {
  list.replaceChildren();

  for (const food of foods) {
    const item = document.createElement("li");
    item.textContent = `${food.name} — ${food.calories} kcal`;
    list.append(item);
  }

  total.textContent = `${totalCalories()} kcal`;
}

Every time the state changes, call render(). That’s it. This is the primitive version of what React does for you.

localStorage

localStorage is a small key-value store in the browser. It survives refreshes and browser restarts.

localStorage.setItem("foods", JSON.stringify(foods));

const raw = localStorage.getItem("foods");
const saved = raw ? JSON.parse(raw) : [];

Three rules:

  1. It stores strings only. Use JSON.stringify to save objects and arrays, JSON.parse to read them back.
  2. It’s per browser and per device. It’s not a database, and it doesn’t sync.
  3. It can throw. Private mode, full storage, or a corrupted value can break JSON.parse. Wrap it in try/catch.
function loadFoods() {
  try {
    const raw = localStorage.getItem("foods");
    if (!raw) return [];
    const parsed = JSON.parse(raw);
    return Array.isArray(parsed) ? parsed : [];
  } catch {
    return [];
  }
}

function saveFoods() {
  localStorage.setItem("foods", JSON.stringify(foods));
}

Call saveFoods() after every change, and loadFoods() once at startup.

Try it

Add a couple of foods, then press Run again. The list should still be there — the playground simulates localStorage between runs. Remove a food and watch the total change.

Preview

Console

Console is quiet. Run the code to see output.

Edit the code, then hit Run (or Ctrl + Enter) and watch the preview. This is a safe sandbox — you can't break the page.

Add a daily target

the plan's verify step

Add a target input (for example, 2,000 kcal) and show how many calories are left. Persist both the foods and the target in localStorage. Then reload the preview with Run and confirm both are still there.

State can be one object: { target: 2000, foods: [...] }. That's how you'll structure it in React.

The mistakes everyone makes

  • Saving an object without JSON.stringify. localStorage stores [object Object], and parsing it back fails.
  • Parsing corrupt data. Wrap JSON.parse in try/catch.
  • Forgetting to render after a state change. The data is correct; the page is stale.
  • Storing derived values. Calculate the total from the foods; don’t save a second copy that can drift.
  • Assuming localStorage is shared. It’s per browser and device.
  • Using localStorage for secrets. It’s readable by any script on the page.
  • Hitting the 5MB limit. It’s fine for a food log; not for images.

State is the data that changes; everything else is derived from it.

Render from state: change the data, then call render().

localStorage stores strings; use JSON.stringify and JSON.parse.

Load once at startup, save after every change.

Wrap parsing in try/catch; localStorage can throw.

UI = f(state). That's the bridge to React.

Next: async and fetch. The calculator is local; now let’s talk to a real API.

Previous: Events and forms: make it react
19

Up next

Async and fetch: talking to an API

An API is a server that answers questions with data. Learn async/await, fetch, JSON, loading states, and error handling — then load real data into the page.

Read now