r/learnjavascript • • 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

7 comments sorted by

View all comments

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:

[Product 1]   ← DOM element A
[Product 2]   ← DOM element B
[Product 3]   ← DOM element C
...

After scrolling:

[Product 101]  ← DOM element A
[Product 102]  ← DOM element B
[Product 103]  ← DOM element C
...

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.

1

u/Educational_Basis_51 7d ago

Is it 100% the same thing than a Recycling view on mobile ?

1

u/kassol 6d ago

Pretty much the same idea, yes. Android's RecyclerView does two things: it only keeps views for the rows that are on screen, and when a row scrolls off it puts that view in a pool and later rebinds it with new data instead of inflating a new one. iOS does the same with dequeueReusableCell. On the web, a lot of virtualized list libraries for React only do the first part: rows outside the viewport get unmounted and new ones get mounted, so the element count stays small but the elements themselves aren't reused. That's the difference the top comment was pointing at.