What are React Fragments and why are they used?
A React Fragment lets you group multiple elements without adding an extra DOM node. Returning a list of siblings from a component requires a single root, but you don't always want a wrapper div in the output.
Two syntaxes — explicit
<React.Fragment>...</React.Fragment>or short form<>...</>.Cleaner DOM — avoids unnecessary
divwrappers that break flexbox/grid layouts or CSS expectations.Lists with keys — use
<React.Fragment key={id}>when mapping; the short form doesn't accept attributes.Required for table rows / list items — you can't wrap
<tr>or<li>elements in adiv; fragments fix that.Zero runtime cost — doesn't emit anything to the DOM.
// Without Fragment (adds unnecessary div)
function UserInfo() {
return (
<div> {/* This div has no purpose */}
<h1>John Doe</h1>
<p>john@example.com</p>
</div>
);
}
// With Fragment shorthand
function UserInfo() {
return (
<>
<h1>John Doe</h1>
<p>john@example.com</p>
</>
);
}
// With keyed Fragment (for lists)
function Glossary({ items }) {
return (
<dl>
{items.map(item => (
<React.Fragment key={item.id}>
<dt>{item.term}</dt>
<dd>{item.description}</dd>
</React.Fragment>
))}
</dl>
);
}The first example adds an unnecessary <div> to the DOM. The Fragment version renders only the <h1> and <p> with no wrapper.
The keyed Fragment example is essential for lists where each iteration returns multiple elements — the short syntax <> cannot accept the key prop.
Know both syntaxes (<></> and <React.Fragment>). The key use case to mention: keyed Fragments in lists.
Explain that Fragments avoid breaking CSS layouts and invalid HTML structures.