State in the DOM
Build something interactive with the DOM as the single source of truth, then feel exactly why frameworks exist.
Build a filterable, sortable product list. No framework, no libraries. Requirements: a search box that filters as you type; sort by name and by price, ascending and descending; a category filter with checkboxes; a live count of visible items; and an empty state when nothing matches.
Build it the obvious way first, update the DOM directly in each event handler. It will work. Get it working before you read the next paragraph.
Now change a requirement, as a real project would: add a "clear all filters" button. Notice what you have to do. The search box has to be emptied, the checkboxes unticked, the sort reset, the list re-rendered, the count updated, the empty state hidden. Six places, and every one of them is a place you can forget.
Then add another: remember the filters in the URL query string so the view can be shared. Now every state change has a seventh place to update, and loading the page with filters in the URL means setting all six controls from it on startup. The number of paths through your code is growing much faster than the number of features.
That is the problem. Not that the DOM is slow or ugly, it is neither. It is that keeping several representations of the same state in sync by hand is work that grows quadratically, and humans are bad at it. Every framework you will meet in Phase 04 is a different answer to exactly this, and they all reduce to the same move: keep the state in one place, describe the UI as a function of it, and let something else do the synchronising.
Finish by refactoring it once toward that idea, by hand. One state object. One render() that rebuilds the list from it. Handlers that only change state and then call render(). It will feel slightly wasteful and it will be dramatically easier to extend, and you will have just written the central idea of React in about forty lines. Write a paragraph in your repo about what got easier and what got worse.
Build this in your own editor
This one runs on your machine rather than in the browser workbench. Work to the outcomes below, then come back and mark it complete.
You should now be able to
- Build an interactive component with no framework
- Describe the specific problem frameworks solve
- Recognise when vanilla DOM is really the right answer
Loading…