Max Wolfen
Max Wolfen

Reputation: 2023

Why Fragments in React 16 is better than containers?

So, I learn React in Depth and now I'm studing on React Fragments. As it described in official docs https://reactjs.org/docs/fragments.html , Fragments are very interesting way to return multiple elements. But I cannot figure out than it is better than the usual component and the transfer of the child through it?

Upvotes: 0

Views: 570

Answers (2)

Singh
Singh

Reputation: 1988

The basic need for fragments is to avoid the usage of an extra parent wrapper that is simply present to cover up it's children. Consider an example below:

return (
  <div>
      <h1>Hello World!</h1>
      <h2>Enjoy your life!</h2>
  </div>
);

Now, one can argue that there is no need for that extra div and he/she would rather prefer removing it. This is where fragments come into picture. It adds the ability to remove the parent wrapper and pass in the children as an array from the return statement. With fragments, the above code would transform into:

return (
   <>
    <h1>Hello World!</h1>
    <h2>Enjoy your life!</h2> 
   </>
);

Upvotes: 2

Sviat Kuzhelev
Sviat Kuzhelev

Reputation: 1788

  1. It is slightly faster and has less memory (there is no need to create an additional DOM node). This gives real benefit only on very large and / or deep trees, but application performance often suffers from death by thousands of cuts. This reduction is less.
  2. Some CSS mechanisms, such as Flexbox and CSS Grid, have a special relationship between parents and children, and adding a div in the middle makes it difficult to keep the desired layout when retrieving the logical components. The DOM inspector is less cluttered: -)

In this React problem, you can find descriptions of some other uses: https://github.com/facebook/react/issues/2127

  1. Added features not available previously with JSX
  2. Improved semantic markup of jsx. Elements of the wrapper are used, if necessary, not because they are forced.
  3. Less common dom layout (increased rendering performance and lower memory costs)

It's as simple as when you do not need a shell element, you do not have to use it. If you take into account fewer elements, but I think the biggest advantage is that they can display elements in jsx that were not previously possible, and add a better semantic value to the shell elements, because now they are optional.

It was impossible before:

<span>
  {this.renderOptions ()}
</span>

Looking at the next in React 15, you can not determine whether the wrapper element is needed or not:

<span>
  <h1> Hello </ h1>
  {this.getContent ()}
</span>

Upvotes: 6

Related Questions