Both React.Fragment and <> </> are used to group multiple elements without adding extra nodes to the DOM, but there are important differences.
πΉ React.Fragment
<React.Fragment key="item">
<h1>Hello</h1>
<p>World</p>
</React.Fragment>
β Features
- Can accept a
key(important in lists) - More explicit and readable
- Works in all React environments
πΉ Empty Tags (<> </>)
<>
<h1>Hello</h1>
<p>World</p>
</>
β Features
- Shorter syntax
- Cleaner JSX
- No extra DOM node
β Limitation
- β Cannot accept
keyor any props
π₯ Key Differences
| Feature | React.Fragment | <> </> |
|---|---|---|
| Extra DOM element | β | β |
Can use key |
β | β |
| Can accept props | β | β |
| Syntax length | Longer | Shorter |
| Use in lists | β | β |
π§ͺ Example (List Rendering)
β This will NOT work
items.map(item => (
<>
<h1>{item}</h1>
</>
));
β Correct way
items.map(item => (
<React.Fragment key={item.id}>
<h1>{item.name}</h1>
</React.Fragment>
));
π― Short Interview Answer
Both
React.Fragmentand<> </>group elements without adding extra DOM nodes.
The difference is thatReact.Fragmentsupports thekeyattribute, making it suitable for lists, while the shorthand syntax does not.
β One-line summary
Use <> </> for simplicity, React.Fragment when you need keys.