Do not Use <div> in React

itsrajcode

Rajan Prajapati

Posted on July 31, 2024

Do not Use <div> in React

We all use <div> everytime when we work in react to wrap elements inside one element.

Image description
In React JSX,
To return multiple components or elements we have to wrap and group and all the elements inside a wrapper like div

But in the most of cases that div is not required at all and it takes an extra space in the DOM but still we have to use it because thats how React works

so React introduces a new feature in React 16.2 which are React Fragments

Now React Fragments works exactly like Div
You can wrap or group with Fragments

Image description

Also u can use Fragments shorthand (<> </>) instead of React.Fragments

Image description

But why to use Fragments ?

1.fast

Div element creates a ode in DOM and occupy some space but React Fragments never creates any node in DOM and never occupy any space which makes the app tiny bit faster

2.Less cluttered DOM

Having lots of nested div makes the DOM large and hard to read or debug but with Fragments, DOM become a little easy to look at and debug

💖 💪 🙅 🚩
itsrajcode
Rajan Prajapati

Posted on July 31, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related