The pain of manual DOM updates
This course assumes two things from earlier courses. From Web Development Fundamentals you know what the DOM is: the browser's live tree of elements that JavaScript can read and change. From Advanced JavaScript you know functions, arrow functions, destructuring, and array methods like map and filter. We will lean on all of them.
React is a JavaScript library for building user interfaces. Before we look at any React code, it is worth feeling the problem it solves, because every React idea makes sense once you see the pain it removes.
The old way: update the DOM by hand
In Web Development Fundamentals you updated pages like this:
const count = document.getElementById("count"); const button = document.getElementById("add"); let clicks = 0; button.addEventListener("click", () => { clicks = clicks + 1; count.textContent = String(clicks); if (clicks >= 10) { count.classList.add("warning"); } });
This is called imperative code: you spell out every DOM change yourself. It works fine for one counter. Now imagine 40 pieces of the page all depend on clicks, plus a filter dropdown, plus a logged-in user. Every event handler must remember to update every affected element. Forget one, and the screen no longer matches the data. That mismatch is the classic source of UI bugs.
React's big idea: describe, don't patch
React flips the model. Instead of writing instructions for how to change the screen, you write a function that describes what the screen should look like for the current data. When the data changes, React calls your function again and updates only the DOM pieces that differ.
This style is called declarative: you declare the result, React performs the steps. Your job shrinks to two things:
- Keep your data correct.
- Describe the UI for any possible data.
The screen can never drift out of sync with the data, because the screen is always recomputed from the data.
Code exercise · javascript
The sync bug, live. addToCartBuggy updates the data and the badge but forgets the checkout line, the exact mistake that slips into real handlers. The declarative fix at the bottom recomputes every dependent string from the data in one place, so it cannot forget. Run it.
Quiz
A page shows a cart icon, a cart page, and a checkout button that all display the number of items. In the manual DOM approach, what must every 'add to cart' handler do?
Quiz
Which sentence best describes declarative UI, React's approach?