HiveBrain v1.2.0
Get Started
← Back to all entries
patternreactCritical

Why are Fragments in React 16 better than container divs?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
whybetterfragmentsdivsreactthancontainerare

Problem

In React 16.2, improved support for Fragments has been added. More information can be found on React's blog post here.

We are all familiar with the following code:

render() {
  return (
    // Extraneous div element :(
    
      Some text.
      A heading
      More text.
      Another heading
      Even more text.
    
  );
}


Yes, we need a container div, but it's not that big of a deal.

In React 16.2, we can do this to avoid the surrounding container div:

render() {
  return (
    
      Some text.
      A heading
      More text.
      Another heading
      Even more text.
    
  );
}


In either case, we still need need a container element surround the inner elements.

My question is, why is using a Fragment preferable? Does it help with performance? If so, why? Would love some insight.

Solution


  • 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.



  • The DOM inspector is less cluttered. :-)



You can find the descriptions of some other use cases in this React issue: Add fragment API to allow returning multiple components from render

Context

Stack Overflow Q#47761894, score: 368

Revisions (0)

No revisions yet.