Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Concept · 15 min · revision 3

Keeping UI and Data in Sync, and Remembering It

Make the screen a function of one state object, persist that state with localStorage without losing data, and observe the page with IntersectionObserver.

Contentsand lesson path

On this page

  1. Why it matters
  2. One state, one render
  3. Remembering with localStorage
  4. Observing instead of listening
  5. Check your understanding
  6. Apply it
  7. Review prompt

Lessons of DOM Manipulation & Events

  1. The DOM as a Live Tree Concept · 15 min
  2. Changing the Page Safely Worked example · 20 min
  3. Listeners, Propagation and Default Actions Concept · 25 min
  4. Lab: A Filterable List Driven by One Delegated Listener Lab · 30 min
  5. Keeping UI and Data in Sync, and Remembering It Concept · 15 min
  6. Check: Find and Fix the Interaction Bugs Knowledge check · 6 questions

What you will learn

  • Render a list UI from a data array, re-render it after each state change, and persist that state with localStorage.

Prerequisites: JavaScript Foundations

01. Why it matters

The lab left you with a working list, and its quietest decision was the most important one: there is one state, and the screen is rebuilt from it. This lesson names that pattern and shows why it prevents a whole family of bugs, then completes the picture with the rules of localStorage — where the state sleeps between visits — and with a platform API that watches the page without any scroll listeners.

The alternative — touching DOM nodes here and there as changes happen — feels natural and fails predictably. Every place that patches the screen must remember every earlier change: hide this row because the filter says so, strike that one because it is done, update the counter twice. Forget one and the screen lies. Bugs of that shape are the ones users report as "it works, then it randomly doesn’t".

02. One state, one render

The pattern has three moves. Collect everything the screen depends on — items, the active filter, any mode — into a single object. Write one render() that reads that object and rebuilds the part of the page it owns. Make every event handler do only two things: change state, then call render(). No handler ever edits a node by hand.

HTML · a pantry list
<h1>Pantry</h1>
<p id="count" role="status"></p>
<ul id="items"></ul>
JavaScript · state in, screen out
const state = { items: ['Milk', 'Tea', 'Rice'], filter: '' };

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

function visibleItems() {
  const needle = state.filter.trim().toLowerCase();
  return state.items.filter(
    (item) => !needle || item.toLowerCase().includes(needle),
  );
}

function render() {
  list.replaceChildren(); // clear the old view in one call
  for (const item of visibleItems()) {
    const li = document.createElement('li');
    li.textContent = item;
    list.append(li);
  }
  count.textContent =
    `${visibleItems().length} of ${state.items.length} shown`;
}

render();
console.log('after first render:', count.textContent);

state.filter = 'ea';
render();
console.log('after filter:', count.textContent);
console.log('items in list:', list.children.length);
Expected output
after first render: 3 of 3 shown
after filter: 1 of 3 shown
items in list: 1

Nobody "hid" two list items: the filter changed, the render followed, and the count could not disagree with the list because both came from the same function. Values like that count are derived: computed from state inside render() and never stored separately, because a second copy is a second thing that can drift. The second render is also why rebuilds should be cheap to reason about: replaceChildren() empties the container in one call, and the loop inserts fresh nodes. A refinement for big lists is to build the new nodes inside a DocumentFragment off the tree and insert once; for lists in the dozens, the rebuild above is already fast enough that you should prefer its simplicity.

The pattern scales by addition, not by cleverness: a sort control adds a sortBy field to state, one line in render(), and one handler that assigns it. A second view of the same data reads the same object. When you later meet React or another UI framework, recognise the shape: state in, interface out, events only ever touch state.

03. Remembering with localStorage

localStorage keeps strings under string keys, per origin, with no expiry date you set: it normally survives closing the browser. It is not guaranteed storage, though — the user can clear it, private windows discard it at the end of the session, and Safari deletes it for a site after seven days of browser use without interaction on that site — so never keep the only copy of important data there. Three rules cover the mistakes. It stores only strings — hand it anything else and it is converted with String(), silently destroying the value, so arrays and objects must go through JSON.stringify and come back through JSON.parse. A missing key reads as null, not as an error and not as an empty array, so give loads a default. Reading and writing can throw — corrupted data fails JSON.parse, and setItem can refuse when storage is full or blocked — so wrap both in try/catch and carry on without persistence.

JavaScript · the three rules in one file
const KEY = 'pantry.v1';

function load() {
  try {
    return JSON.parse(localStorage.getItem(KEY)) ?? [];
  } catch {
    return []; // the stored text was not valid JSON
  }
}

function save(items) {
  localStorage.setItem(KEY, JSON.stringify(items));
}

save(['Milk', 'Tea']);
console.log('after save:', JSON.stringify(load()));

localStorage.setItem(KEY, '{oops'); // corrupted by an older version
console.log('after corruption:', JSON.stringify(load()));

localStorage.removeItem(KEY);
console.log('first visit:', JSON.stringify(load()));
Expected output
after save: ["Milk","Tea"]
after corruption: []
first visit: []

Name keys the way you name an API: pantry.v1, not data. The version suffix means a later, incompatible change to the item shape can move to v2 and migrate or discard the old value, instead of crashing on it. Two smaller notes for later: sessionStorage has the same API but clears when the tab closes, and the storage event fires in other tabs of the same origin when a key changes — the standard hook for keeping two tabs of the same app in step. Keep personal data out of web storage unless you have decided deliberately that plain, per-origin strings are acceptable for it.

04. Observing instead of listening

The state-and-render pattern covers changes you cause. For changes the browser knows about first — an element scrolling into view, the size of a container — the platform has observers: you register interest once, and the browser calls you back. IntersectionObserver reports when an element enters or leaves the viewport, which replaces the classic scroll handler and its arithmetic with three lines:

JavaScript · knowing when the end of the page is visible
// The page is taller than the window and ends with <p id="end">.
const sentinel = document.querySelector("#end");

const observer = new IntersectionObserver((entries) => {
  for (const entry of entries) {
    console.log(
      `${entry.target.id}: isIntersecting=${entry.isIntersecting}`,
    );
  }
});
observer.observe(sentinel);
console.log('observing; no callback yet');
Expected output (first two lines on load, third after scrolling to the bottom)
observing; no callback yet
end: isIntersecting=false
end: isIntersecting=true

Read the timing, because it teaches how observers behave. The synchronous log ran first; the first callback arrived after it, reporting the element just below the fold as not intersecting — observe() always delivers the current state once, even if nothing changes afterwards. Scrolling to the bottom produced the second callback, now true. That is the pattern for "load more when the footer shows" or "animate the card that appears": state changes reported to you, with no handler multiplying across scroll events. The same register-and-forget shape appears elsewhere in the platform — MutationObserver reports DOM changes and ResizeObserver reports size changes — and they all pair naturally with the one-render design: an observer updates state and calls render(), and nothing else.

05. Check your understanding

Practice check · 3 questions

Design decisions

Choose the design that survives growth.

Q1. The list grows a "sort by name" control. Under the one-state, one-render design, what is the change?
Q2. When updating a list with many items, what is the main benefit of appending into a `DocumentFragment` before inserting, rather than appending each `li` to the live list in a loop?
Q3. When can `localStorage.setItem()` throw?
Practice only: not graded, not saved, not evidence.

06. Apply it

Return to the lab list and push it towards the full shopping-list practice:

  1. Add filterMode ("all", "done", "to-do") to state with a labelled select; one line in visibleItems() and one handler.
  2. Show a "3 of 5 done" summary in the live region; derive it inside render() from state.
  3. Move the storage key to v2 and write the migration: if v1 exists, read it, convert it, save under v2, remove v1.
  4. Observe the list with an IntersectionObserver and log when the last row becomes visible — the hook for "load more" pages later.

07. Review prompt

Without looking back: what are the three moves of the one-state, one-render pattern, and which bug family does it prevent? Recite the three localStorage rules and the reason for each. What does an IntersectionObserver deliver on observe() before anything changes, and how would you wire one into the render pattern?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check