What are 'fragments' in React?

Understanding React Fragments

React Fragments are a unique feature of React that allows a component to return multiple elements. If you have worked with React, you would know that typically, each component in React returns a single JSX element. However, there are situations where it would be more convenient or semantically correct to group a list of children without adding extra nodes to the DOM. In these situations, React Fragments come into play.

Here, let's illustrate this concept with a simple example:

import React from 'react';

function ExampleComponent() {
  return (
    <React.Fragment>
      <h2>First Element</h2>
      <h3>Second Element</h3>
    </React.Fragment>
  );
}

export default ExampleComponent;

In this example, the ExampleComponent is returning two JSX elements, h2 and h3, wrapped in a React.Fragment. This React.Fragment allows these two elements to be rendered without the need for a parent div or any other extra elements.

It's important to note that as of React 16.2, there is now a shorter syntax for declaring fragments. It looks like this:

import React from 'react';

function ExampleComponent() {
  return (
    <>
      <h2>First Element</h2>
      <h3>Second Element</h3>
    </>
  );
}

export default ExampleComponent;

Again, the ExampleComponent is returning two elements. However, this time we used <> and </> to declare a fragment. It’s a little bit cleaner and less verbose than React.Fragment.

The major advantage of React Fragments is that they don't produce any additional HTML. This can be a great help in keeping your UI lean and your DOM structure as stable as possible, which can improve performance and make a real difference for large applications.

As you continue to build with React, try to incorporate Fragments where intuitive, for a cleaner codebase and better app performance. Remember, best practices in using Fragments include only using them when logically grouping multiple child components together, and when you want to reduce extra nodes in your DOM.

Do you find this helpful?