What are React Fragments, and why are they used?

Answer

React Fragments let you group multiple elements without adding an extra node to the DOM. They help avoid unnecessary wrappers, keeping the DOM clean.

Syntax:

import React from "react";

function App() {
  return (
    <>
      <h1>Hello</h1>
      <p>This is a React fragment example.</p>
    </>
  );
}

Alternatively:

import React from "react";

function App() {
  return (
    <React.Fragment>
      <h1>Hello</h1>
      <p>This is a React fragment example.</p>
    </React.Fragment>
  );
}

Fragments improve performance by reducing the DOM tree size.

Read more about React Fragments