6 React Tips:

When To Use Div Vs Fragment in React

What is Fragment ?

React components can only return one parent element. Instead of wrapping child elements in a <div>, can be used <Fragment> or <> </>

No Need Extra DOM

WIth the help of Fragment we can wrap the entire jsx which suppose to return, adding exatr DIV can lead to additional DOM.

Legacy Version

In legacy version of the react it was used <Fragment> component to wrap the contents. It was required to import component explicitly.

Why DIV ?

The <div> element is commonly used as a generic container. It wraps child elements and creates a single node in the DOM tree.

Fragment Use

Since JSX expects only one return element, the most common use case for a fragment is to wrap all elements in a single fragment to ensure a valid return.

DIV for CSS

<div> can be used to add the className , id or inline style to a <div>, which is not possible with a Fragment.

DIV for Layout

<div> elements help build the page layout — used for columns, sections, grids, cards, etc.

Fragment Pros

By using the fragment extra node can be avoided, it also improves the performance and maintain valid HTML structure. Fragment leads to cleaner code.

Thanks for Reading !

Also Read: Secret to create javascript objects for seniour dev