This content originally appeared on Go Make Things and was authored by Go Make Things
Yesterday, I shared my latest YouTube video on how to build a modern web app with vanilla Web Components.
If you missed it, the tl;dr is that users can add items to a list (ul
) using a form. Then, they click a button
to pick item from the list at random.
The code for picking the items looks like this…
/**
* Handle click event
* @param {Event} event The event object
*/
onclick (event) {
// Get all of the list items
let items = Array.from(this.list.querySelectorAll('li')).map(function (item) {
return item.textContent;
});
// Randomize the items
this.shuffle(items);
// Show the result
this.result.textContent = `You picked ${items[0]}`;
}
One viewer asked a question:
Why not store the items as an array instead of getting them from the DOM each time?
It’s a great question!
In most modern JS apps, you’d do something like this instead…
// Get an immutable copy of the items
let items = Array.from(this.items);
// Randomize the items
this.shuffle(items);
// Show the result
this.result.textContent = `You picked ${items[0]}`;
But as Jeremy Keith wrote in his article on HTML Web Components…
Try not to bring React’s mindset with you…
Think about composibility with existing materials. Do you really need to invent an entirely new component from scratch? Or can you use HTML up until it reaches its limit and then enhance the markup?
Web Components are very much with the grain of the web.
Storing your data in JavaScript objects is a React convention. It absolutely makes sense in certain situations, but in this app, it would just add more complexity.
If my items
were also kept an array, every time I add an item, I also need to update the array. If I delete an item, I need to go back to the array, find that item, and remove it.
It’s simpler and less buggy to let the DOM be the state of the app, and query it when needed.
This content originally appeared on Go Make Things and was authored by Go Make Things

Go Make Things | Sciencx (2024-06-21T14:30:00+00:00) Keeping state in the DOM vs. state in a JavaScript object. Retrieved from https://www.scien.cx/2024/06/21/keeping-state-in-the-dom-vs-state-in-a-javascript-object/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.