Zephyrnet Logo

Why we shouldn’t use in React JS

Date:

As we know, we typically use DIV to make a container or wrap multiple elements inside one element and then can apply styling on them at once.

In React JSx, we commonly use div to put multiple components inside of it to return as a single component.
As you can see below:

return (
<div> <Home /> <Main /> <Blogs /> <footer />
</div>
)

Although, we can eliminate the DIV and free up some extra space in DOM.
Here are some alternatives that we can use instead of DIV around the components.

React Js version 16.2, introduces a new feature the Fragmentation concept. Let’s look into it more deeply.

Now React Fragment works exactly the same as DIV as a wrapper around components.
See this example :

return (
<React.Fragment> <Home /> <Main /> <Blogs /> <footer />
<React.Fragment />
)

OR we can use the Fragment shothand tag (< > < />) snippet instead of <React.Fragment>

this is exactly the same as <React.Fragment>

return (
<> <Home /> <Main /> <Blogs /> <footer />
< />
)

Benefits of Using Fragment:

1. FAST
As we know DIV tag creates a node in DOM and occupies some space in DOM, but React. The fragment does not create a node in DOM, so it will not take any space in DOM
which makes the application bit faster than usual.

2. Less Cluttered DOM
Having many irrelevant nodes make code messy and hard to read when the application grows. as we could have multiple parent component with nested child component, which make our code messier and becomes a barrier to debugging the code in a proper way But with Fragment, code looks more clear and easy to understand and debug.

Conclusion:
Using Fragment in the latest version of React will be considered a good practice to follow. Most developers don’t pay attention to little things like this, which could help to destroy application architecture when it grows in the future.

Except there are no exceptional criteria for that we must have to use the DIV to add some classes and add style to it.

Thank you very much for your support. Follow and share with your colleagues.
Stay tuned for upcoming articles like this.

Stay Safe! Stay Happy!

spot_img

Mobile

Latest Intelligence

spot_img