Why Use Fragments?
Without fragments, you’d need to wrap multiple elements in a container:<div> can cause issues with:
- CSS layouts (flexbox, grid)
- Table structures
- List semantics
- Extra DOM nodes affecting performance
Using Fragments
- JSX Syntax (Recommended)
- Explicit Fragment
The most common way to use fragments is with the short syntax This renders the children without any wrapper element in the DOM.
<>...</>:How Fragments Work
TheFragment component is implemented simply in src/create-element.js:
src/create-element.js:77-79
Common Use Cases
Keyed Fragments
When rendering a list of fragments, you need to provide akey prop. The short syntax <> doesn’t support keys, so use the explicit Fragment component:
Fragments vs. Arrays
You might wonder: why use fragments when you can return an array?- With Fragments (Recommended)
- With Arrays
- More readable JSX syntax
- No need for keys on static elements
- Consistent with React
Practical Examples
Best Practices
Performance Considerations
Fragments have no performance overhead - they don’t create extra DOM nodes or components. They’re just a syntax feature that tells Preact to render children directly.Next Steps
Server-Side Rendering
Render Preact components on the server
TypeScript
Use Preact with TypeScript for type safety