DEV Community

Mickaelo
Mickaelo

Posted on

React Fragment VS Div

Div tag

<div>
   Hello world
</div>
Enter fullscreen mode Exit fullscreen mode

A div has the prototype chain HTMLDivElement - HTMLElement - Element - Node - EventTarget, whereas a document-fragment has DocumentFragment - Node - EventTarget. This means a div has more methods and properties available (like innerHTML).

React Fragment Tag

<React.Fragment>
   Hello world
</React.Fragment>
Enter fullscreen mode Exit fullscreen mode
  • The fragments eliminate the wrapper div which can cause problems with invalid HTML and with styling of the components plus the fact that they are faster and the DOM is less cluttered, I’d say they are worth using.

Short syntax:

<>
   Hello world
</>
Enter fullscreen mode Exit fullscreen mode

You can't add properties like key with this syntax.

React Fragment advantages

  • Code readability
  • Added features not possible before with JSX
  • Better semantic jsx markup. Wrapper elements are used when needed not because they are forced to.
  • Less overall dom markup (increased render performance and less memory overhead)

Conclusion:

It’s a tiny bit faster and has less memory usage (no need to create an extra DOM node). This only has a real benefit on very large and/or deep trees, but application performance often suffers from death by a thousand cuts. This is one cut less.
Some CSS mechanisms like Flexbox and CSS Grid have a special parent-child relationship, and adding divs in the middle makes it hard to keep the desired layout while extracting logical components.

Top comments (1)

Collapse
 
starnlyr profile image
Starnlyr

I need collaborate inbox via my email: starnlyroberson369@vish_sabhadiya_d13069b02c