Return to site

[React] Fragment the memory efficient way

· react

We all use

whenever we work in HTML to make containers 📦 or wrap elements in one element.

We use

return (
  <div>
   <Component1 />
<Component2 />
<Component3 />
</div>
)

to return multiple components wrapped into a div so we can group them.

In most cases, that div is unnecessary and takes extra space in the DOM.

But in React 16.2, React introduces the 'Fragment' feature 🆕.

React Fragment works exactly like a div, you can wrap or group multiple elements with Fragments:

return (
  <React.Fragment>
   <Component1 />
<Component2 />
<Component3 />
</React.Fragment>
)

or with the shorthand (<>):

return (
  <>
   <Component1 />
<Component2 />
<Component3 />
</>
)

There are advantages to using Fragments:

1️⃣ It is fast: the div element creates a node in DOM and occupies some space 💾 but React Fragments never creates any node in DOM and never occupies any space ❌💾.

2️⃣ It is a more Readable DOM 👓: having lots of nested div makes the DOM large and hard to read and debug, but with Fragments, it gets cleaner 👍.

#react #fragment #fullstack

 

Section image