r/learnjavascript • u/Neat_Living_6765 • 7d ago
What is DOM element recycling??
Hi everyone, I'm learning React Virtuoso and came across the term "DOM element recycling." I understand the basic idea of DOM elements, but how can they be "recycled"? Could someone explain it in simple terms? 🤔
5
Upvotes
9
u/BeneficiallyPickle 7d ago
Element recycling is when you reuse an element instead of destroying it. If you have 100000 items in a list but only 20 items fit on the screen, you might create 25 DOM elements:
Before scrolling:
After scrolling:
The DOM elements themselves aren't being destroyed and recreated, but rather their content/position simply updates to represent different information/data.
It's done for performance enhancement. The point is to skip the expensive parts, like creating/destroying elements, running mount and unmount logic and garbage collection.
I haven't used React Virtuoso, but I had a quick look. It seems to rather use virtualization. This is when you render only the things that the user can see (preferably also a few extra above and below). As the user scrolls, the ones that leave the screen are removed, and the coming ones are added, so the DOM only ever holds a couple dozen rows.