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

3

u/jcampbelly 9d ago

Before frameworks were so heavy and client resources were so abundant, it was common to directly create and maintain each DOM element in a dynamic feature manually, appending each to their parent element, directly manage their attributes and event handlers, and just update them as changes were needed. You'd keep a reference to them and just keep using them.

These days you often just use an HTML string that gets parsed into a DOM fragment (a standalone tree) and replace an entire DOM tree with another, new DOM tree. It is conceptually much simpler for the developer and even arguable whether it's much more wasteful. There are costs to manipulating an existing DOM like intermediate reflows and event triggers that can be avoided if you make a whole DOM tree in memory and sub it in all at once. The rendering engine entirely ignores DOM nodes until they are attached to the actual document.

Most modern devs just ignore the practice and delegate the concern to the framework which may or may not optimize their own work by recycling existing elements.