When state scatters
This lesson is the course's pivot. Everything has grown smoothly so far. Now we'll see where the "simple" way of managing state leads — and why that pain is necessary.
Look at how state has accumulated. Lesson 6 added isLoading and error. Lesson 7 — searchQuery. Add the collection's (lesson 10) collectionQuery, sortKey, currentPage, pageSize, plus pictures, favorites, daysToShow — and you have about ten loose variables, scattered across main.js. That's the app's entire memory, with no owner.
And here's the problem. Three views depend on the same favorites:
- The gallery — whether each card's ♡ is filled.
- The collection — whether a row exists for that picture.
- The home page — the "saved" counter.
When favorites changes (you click ♡), all three must re-render. And who re-renders them? You, by hand — every action has to call renderGallery() AND renderCollection() AND renderHome().
While there are few actions, it seems manageable. But every new action must know all the views that depend on the data it touches. And nothing — not the compiler, not the browser — warns you if you forget one. The DOM and the data start to diverge, and only your memory holds them together. Memory fails.
In this lesson we'll reproduce and see that bug — a silently lying screen. Because this is exactly what the pub/sub in lesson 9 solves, and exactly why the TypeScript arc later "lands". If this lesson doesn't hurt, everything after it falls flat.