Europe/Kyiv
Posts

React Fragments: <> or <React.Fragment>?

March 1, 2025
In the React world, we constantly strive for clean and efficient code. Fragments are one of the key tools for that — but choosing between the short (<>) and full (<React.Fragment>) syntax has important technical implications. Both options solve the same problem — grouping elements without creating an extra DOM node. This is the foundation of clean, semantic markup. A concise and convenient way for simple grouping. Its main characteristic — it does not support any attributes.
function Component() {
  return (
    <>
      <h1>Title</h1>
      <p>Description</p>
    </>
  );
}
A full-featured component that allows passing attributes. The most important one is key.
function List({ items }) {
  return items.map((item) => (
    <React.Fragment key={item.id}>
      <dt>{item.term}</dt>
      <dd>{item.description}</dd>
    </React.Fragment>
  ));
}
The difference comes from how JSX is compiled into JavaScript:
// <React.Fragment key={id}> compiles to:
React.createElement(React.Fragment, { key: id })

// <> compiles to:
React.createElement(React.Fragment, null)
With <>, props is always null — so passing a key is simply not possible. This is not a syntax limitation, it's a consequence of compilation. Trying to pass key to the short syntax results in an error:
// ❌ Does not work — syntax error
items.map((item) => (
  <key={item.id}>
    <dt>{item.term}</dt>
    <dd>{item.description}</dd>
  </>
));

// ✅ Correct
items.map((item) => (
  <React.Fragment key={item.id}>
    <dt>{item.term}</dt>
    <dd>{item.description}</dd>
  </React.Fragment>
));
  • Use <> for static grouping of elements where a key is not needed.
  • Always use <React.Fragment key={...}> inside .map() — the key is critical for React's reconciliation algorithm.
Were you thinking about this before, or just using <> everywhere? 😅