The Difference Between <></> and <React.Fragment>

When learning React, you may occasionally confuse <></> and <React.Fragment>. These are used to wrap multiple elements in React and in most cases, you use the modern syntax of <>. In simple terms, they are almost the same or equivalent.


Why Use React.Fragment?

In React, components are typically required to wrap in a single parent element.

  • Name
    <React.Fragment>
    Type
    Description

    To address this issue, React introduced the concept of Fragment. Fragment allows you to group multiple elements together or return multiple child elements without a parent element.

  • Name
    <>
    Type
    Description

    <></> is a shorthand syntax for React.Fragment.

<React.Fragment>

function App() {
    return (
        <React.Fragment>
            <ChildA />
            <ChildB />
            <ChildC />
        </React.Fragment>
    );
}

<>

function App() {
    return (
        <>
            <ChildA />
            <ChildB />
            <ChildC />
        </>
    );
}

The Difference Between <></> and <React.Fragment>

There is no functional difference between these two approaches, and they mostly serve the same purpose.

  • Name
    Key Props
    Type
    Description

    React.Fragment supports key props, but the shorthand <></> does not. Therefore, when you need to use a Fragment inside a loop, such as with map, you'll need to use React.Fragment.

  • Name
    Developer Preference
    Type
    Description

    Some developers may find <React.Fragment>...</React.Fragment> more readable than the shorthand <>...</>.

  • Name
    Compatibility
    Type
    Description

    Since not all tools may support the shorthand syntax, using React.Fragment is recommended when compatibility is a concern.

<React.Fragment>

function List({ items }) {
    return items.map(item => (
        // key prop is needed when creating a list of elements
        <React.Fragment key={item.id}>
        {/* ... */}
        </React.Fragment>
    ));
}

Conclusion

Therefore, the choice between these two methods largely depends on style and personal preference.

Using React Fragment or <></> provides a performance advantage as it does not create additional nodes in the DOM. In other words, using <React.Fragment> or <></> is more efficient than wrapping with <div> or other HTML tags. However, this is a general case, and it's not always the case, so you should choose appropriately based on the situation.