Nested Fragments and Common Patterns
What you'll learn: When and why you'd nest fragments inside other fragments, and how excessive fragment nesting often signals it's time to extract a component.
The Core Idea
You can absolutely place a fragment inside another fragment. This happens naturally when you compose components that themselves return fragments. While technically valid, deeply nested fragments often indicate your component is doing too much and needs refactoring.
When Nested Fragments Appear
function UserProfile({ user }) {
return (
<>
<h1>{user.name}</h1>
<>
<p>Email: {user.email}</p>
<p>Location: {user.location}</p>
</>
<>
<h2>Bio</h2>
<p>{user.bio}</p>
</>
</>
);
}
This works perfectly fine—React flattens all fragments. But notice how the inner fragments group related content? That's a smell that suggests these groups want to be their own components.
The Refactoring Signal
Think of nested fragments like nested folders on your computer. One level? Fine. Three or four levels deep? You're probably organizing wrong. When you find yourself grouping JSX with fragments within a component, ask: "Should this group be its own component?"
The refactored version:
function ContactInfo({ email, location }) {
return (
<>
<p>Email: {email}</p>
<p>Location: {location}</p>
</>
);
}
function Bio({ content }) {
return (
<>
<h2>Bio</h2>
<p>{content}</p>
</>
);
}
function UserProfile({ user }) {
return (
<>
<h1>{user.name}</h1>
<ContactInfo email={user.email} location={user.location} />
<Bio content={user.bio} />
</>
);
}
Now each component has a clear responsibility, and nesting happens through composition, not fragment stacking.
Key Takeaway: Nested fragments are legal and sometimes necessary, but if you're manually nesting fragments to organize chunks of JSX, that's usually React telling you to extract components instead.