Why Frameworks, and Why React
Trailhead shows "3 saved" in the header, a filled heart on each saved trail card, and a list of saved trails in the sidebar. When the hiker saves a fourth trail, all three places must change together. Doing that by hand is where web pages start to fall apart, and it is the reason frontend frameworks exist.
The rule
Describe the screen for the data; let the framework do the edits.
Without a framework you write imperative code: find each element and change it.
// Plain DOM: every place that shows the count is your job
saved.push(trail);
document.querySelector("#count").textContent = saved.length;
heartButton.classList.add("filled");
sidebarList.appendChild(makeItem(trail));Add a fourth place that shows the count and you must remember to update it too. Forget once and the page contradicts itself.
A frontend framework flips this to declarative code. You keep the data in one place and write what the screen should look like for that data. When the data changes, the framework works out which parts of the page need editing.
Why React in particular:
- Components: the UI is built from small functions like
TrailCardandSavedCountthat you can reuse and test on their own. - State drives rendering: change the state, and React renders again and applies only the differences to the page.
- One-way data flow: data passes down through props, so you can trace where any value came from.
- Ecosystem: a huge number of libraries, tools and developers, and it is the base Next.js is built on.
function SavedCount({ saved }) {
return <span>{saved.length} saved</span>;
}SavedCount never "updates" anything. It just describes the answer for the data it receives.
The shortcut
For any interface change, ask "What data changed?" instead of "Which elements do I edit?" Update the data; the screen follows.
Change the data
Call
setSaved([...saved, trail]). That is the only line you write for the event.
The trap is carrying the old habit into React: reaching for document.querySelector to patch the page. That fights React, which will overwrite your edit on its next render.
Drills
Answer fast — trust the rule.
What does "declarative" UI mean?
A hiker saves a trail. In React, what should your event handler do?
Which is a direct benefit of one-way data flow?
Why does editing the DOM directly inside a React component cause bugs?
Remember
- Describe the screen for the data; let the framework do the edits.
- Shortcut: ask "what data changed?", not "which elements do I edit?"
- Trap: patching the DOM by hand inside React.
