Return to site

[React] Fragment the memory efficient way

· fullstack,react

We all use

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

We use

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:

or with the shorthand (<>):

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

 

broken image