Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> "A pure function which transforms the entire input into the entire output" is obviously the simplest possible architecture for many programs, but people hesitate to use that architecture because of performance concerns. In practice, the baseline performance is often faster than they expect, and it can be made much, much faster using strategies like memoisation and fine-grained reactivity.

But before React came along, you just couldn't do this without major UX breaking bugs, because of how the DOM worked.

Say you have a form that you want to change depending on the state of the app. If the user is typing in a form field while an update to the app state comes, and a pure function that transforms (app state -> DOM/HTML output) resets the form (meaning removing the old out of state DOM and replacing it with the new DOM), the user loses focus on the form. So you have to add some kind of logic where the app remembers what form input the user was focused on, where in the field the focus was, etc. The more complex your app is, the more complex the DOM reset logic became, and you cannot abstract your way out of it with pure functions, because the DOM that relies on mutation slowly creeps into your pure functions anyway.

React changed this, because it gives you a pure function interface, but resets the DOM using mutation functions i.e. native DOM methods, surgically. This is achieved with the VDOM (Virtual DOM), by diffing VDOM states and then reflecting that to the actual DOM. This means when the DOM resets, there's no problem with elements getting removed and added back in, and the focus states etc. don't get thrown away with the DOM. Before React, nothing like this existed.



> If the user is typing in a form field while an update to the app state comes

Could you give a practical example of what you mean here? I can't quite wrap my head around what kind of interaction you're describing.

Do you mean some kind of scenario like a shared document with multiple people editing it? This is a very niche case.

> This means when the DOM resets, there's no problem with elements getting removed and added back in,

Could you give a practical example of this? I've been building web apps for a long time and I don't know what "when the dom resets" means.


The problem described by antris is that, if a developer were to naively tear down and rebuild the entire DOM tree on each state change, the browser would discard some important state which belongs to the old DOM nodes. This state includes the text selection, keyboard focus, mouse capture, scroll position, and the progress of CSS transitions and animations.

React solves this problem by building a virtual DOM, and then conservatively updating the actual DOM (sometimes just mutating individual HTML attributes!) so that this state is preserved.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: