Use React Fragments or shorthand syntax "<>" instead of enclosing tags to reduce the amount of DOM elements created.

Use React Fragments or shorthand syntax "<>" instead of enclosing tags to reduce the amount of DOM elements created.

Β·

2 min read

Table of contents

No heading

No headings in the article.

When it comes to developing performant and efficient web applications, one of the key factors to consider is the number of DOM elements being created. The more elements you have, the slower your application will be. Fortunately, React provides a way to reduce the number of DOM elements created by using React Fragments or the shorthand syntax "<>".

What are React Fragments?

React Fragments are a feature introduced in React 16.2 that allows you to group a list of children without adding extra nodes to the DOM. Instead of using a <div> or any other enclosing tag, you can use a <React.Fragment> tag or shorthand syntax "<>" to group elements together.

For example, consider the following code:

<div>
  <p>Hello</p>
  <p>World</p>
</div>

This code will create an <div> element in the DOM, which is unnecessary. Instead, you can use React Fragments like this:

import React from 'react';

function App() {
  return (
   <>
      <p>Hello</p>
      <p>World</p>
  </>
  );
}

This code will only create two <p> elements in the DOM, without the need for an extra <div> element.

Why use React Fragments?

Using React Fragments has several advantages:

  1. Improved performance: By reducing the number of unnecessary DOM elements, your application will perform better, especially on slower devices or in low-bandwidth situations.

  2. Improved readability: React Fragments make your code cleaner and easier to read, as you don't have to worry about extra enclosing tags cluttering your code.

  3. Improved accessibility: React Fragments can help improve the accessibility of your application by reducing the number of extraneous elements that assistive technologies need to navigate.

How to use React Fragments?

Using React Fragments is easy. You can either use the <React.Fragment> tag or shorthand syntax "<>" to enclose your elements. For example:

import React, { Fragment } from 'react';

export default function Poem() {
  return (
   <React.Fragment>
      <p>Hello</p>
      <p>World</p>
   </React.Fragment>
  );
}

or

function MyComponent() {
  return (
    <>
      <p>Hello</p>
      <p>World</p>
    </>
  );
}

Conclusion:

Using React Fragments or the shorthand syntax "<>" is a simple but effective way to reduce the number of unnecessary DOM elements in your web application. By doing so, you can improve the performance, readability, and accessibility of your code. So the next time you need to group elements together, consider using React Fragments instead of enclosing tags.

Β