skip to Main Content

React.Fragement looks like DocumentFragment. But does React.Fragment has the same performance benefits like DocumentFragment?

In other words, are this

// index.jsx

const arr = [...Array.from({length: 10000})];

return (
  <ul>
    <>
      {arr.map((x, i) => <li>{i}</li>)}
    </>
  </ul>
)

and this

// index.js

const arr = [...Array.from({length: 10000})];
const fragment = new DocumentFragment();

for(let i = 0; i < arr.length; ++i) {
  const li = document.createElement('li');
  
  li.textContent = i;
  fragment.append(li);
}

document.querySelector('ul').append(fragment)

the same?

Or I still should use DocumentFragment for large data like below?

//index.jsx

const arr = [...Array.from({length: 10000})];
const fragment = new DocumentFragment();

for(let i = 0; i < arr.length; ++i) {
  const li = document.createElement('li');
  
  li.textContent = i;
  fragment.append(li);
}

return (
  <ul>
    {fragment}
  </ul>
)

2

Answers


  1. Interesting question, I’m pretty sure React.Fragment is not implemented through DocumentFragment, because my guts feeling there’s no such need.

    React.Fragment is simply added to make sure we can do

    <>
      <div>
    </>
    

    But in case we want to specify the element type, we can use React.Fragment. I’m sure you already know what it does, it’s a wrapper that allow you to wrap around a group of elements without adding the physical wrapper element to the DOM. That’s the only purpose for React.Fragment. It has no performance tuning at all.

    Login or Signup to reply.
  2. But does React.Fragment has the same performance benefits like DocumentFragment

    They have a comparable purpose in two not comparable worlds and therefore the implications are different.

    The React Fragment in your first example will impact the performance negatively. Barely measurable, but still. That is because it is an additional node in the node tree that React has to deal with, but without adding any value whatsoever to the code.

    Adding keys to the items in your list has a way bigger impact on performance.

    In other words, are this … and this … the same?

    Your two examples are barely comparable. The major work in React is not creating and mounting the elements, it is updating them every time something triggers a render. And that means first determining which Elements need to be updated.

    Or I still should use DocumentFragment for large data like below?

    this code snippet is nonsensical and will just crash. A JSX Element and a DOM Node are two completely different things. Like apples and oil paintings.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search