Understanding the DOM, Part 2
In the last post, we left off with a question. What’s wrong with this code?
The problem is this line:
Remember that the DOM is for representation. Here, we’re using the DOM to manage state, as if it were a database. We could easily imagine this code being SELECT color FROM DOM WHERE id="example-element";
.
If we treat the DOM properly and use Clojurescript’s built in state management, we can start to separate these conflated issues.
We keep our state in an atom
and transition the state as needed. This is a completely separate concern from rendering. What does that get us?
- The logic for managing state is easier to recognize and understand. It is simple.
- We can easily test
update-color
(our state management) without any dependency on the DOM. - It’s faster. Interacting with the DOM is SLOW; we get a major performance win anytime we avoid it.
- If we change our representation layer (e.g. to iOS/Android), we’re not touching our state logic.
So here’s your guideline: Don’t query the DOM.
If you don’t query the DOM, you’ll be forced to use other facilities for state management, which is exactly what we want.
Thanks to Cognitect for Pedestal App and Facebook for React. Pedestal (no longer actively developed) was the first library to help me see this and React really helped me grok it.