EzioMercer
EzioMercer

Reputation: 2005

Is a React.Fragment the same as a DocumentFragment?

React.Fragment 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>
)

Upvotes: 0

Views: 420

Answers (2)

Thomas
Thomas

Reputation: 12637

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.

Upvotes: 1

windmaomao
windmaomao

Reputation: 7671

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.

Upvotes: 0

Related Questions