The point is that you don't do this. You do:
const App = () => {
// Client-side counter
const [count, setCount] = useState(0);
useEffect(() => {
setTimeout(
() => {setCount(count+1)},
1000
);
}, [count, setCount]);
// HTML-rendering part
return (
<div>Count: {count}</div>
);
}
The framework (next, fresh, whatever) grabs this and generates:- Some sort of "bundle.js" that contains the component (as well as the framework to render it).
- An "index.html" that contains "<div>Count: 0</div>" (and references the above bundle).
- When the "bundle.js" is loaded, it runs the App component in the browser and reconciles the in-memory vdom with the browser's dom (that has the div because it came in the .html)
- From then on, the component runs normally (i.e.: the counter keeps increasing and you see it increase on the screen).
In vanilla-land, you would:
- Write "<div>Count: <span id="count">0</span></div>" in an index.html that also loads a "counter.js"
- Write the counter.js file with something like:
document.addEventListener('ready', () => {
const count = document.getElementById('count');
let value = 0;
setInterval(() => {
count.innerText = value++;
}, 1000);
});
Less code, you don't need frameworks, hydration nor anything similar and it's probably much more performant.However:
- If you want to change the counter's initial value, you have to update both the html and the js file
- If another dev adds some element with id="count" to the html the whole thing breaks.
- If you want to modify the generated html structure, you have to edit both the html and js file
- When the logic gets more complex, you will have to implement it both in your backend-code-that-generates the html as well as in the js
That is, even though it doesn't seem like it in a simple example such as this one, the developer ergonomics of having a vdom are much better when things get hairy. The million dollar question then becomes "how can we achieve a performance and code-size similar to the vanilla approach while keeping the ergonomics of the vdom".
vdom keeps being mentioned, but it doesn't matter here because it's implementation detail, other frameworks will do it differently.
I don't see it's ended up being different than js as yet another backend language with a separate js for volatile state on ui.