What are Fragments in React and Why Use Them?
In React, Fragments are a lightweight way to group multiple elements without adding an extra node to the DOM.
Normally, when you return multiple elements from a React component, you need to wrap them in a parent element like a <div>
. However, this extra <div>
can sometimes mess with your HTML structure and styling (especially when you're building tables, lists, or flexible layouts). Fragments solve this problem by letting you group elements without creating an actual DOM element.
Syntax:
You can use Fragments in two ways:
1. Using <React.Fragment>
:
return ( <React.Fragment> <h1>Title</h1> <p>Description</p> </React.Fragment> );
2. Using shorthand <> </>
:
return ( <> <h1>Title</h1> <p>Description</p> </> );
Both approaches do the same thing — they group the elements without introducing an extra DOM node.
Why Use Fragments?
- Avoid Unnecessary HTML: Keeps the DOM clean and avoids extra divs (
div soup
). - Better Performance: Reduces the number of DOM nodes, leading to slightly better rendering performance.
- Better Semantic Structure: Maintains correct HTML structure (especially useful in elements like tables).
- Clearer Code: Makes your component code cleaner and easier to read.
Example Without Fragment (Extra <div>
created):
return ( <div> <td>Row 1</td> <td>Row 2</td> </div> );
This would cause invalid HTML if used inside a <table>
.
Example With Fragment (No Extra Node):
return ( <> <td>Row 1</td> <td>Row 2</td> </> );
Now the markup is correct!
Quick Notes:
- Fragments can also accept keys if you use
<React.Fragment>
instead of<>
. - Useful when rendering lists and you want to avoid extra wrappers.