How to Update React Fragments in React
React Fragments allow you to group a list of children without adding
extra nodes to the DOM. While Fragments themselves do not hold state or
support traditional lifecycle methods, you can update them by modifying
the state of their parent component or by using the key
prop on a declared <React.Fragment> to force a
re-render. This article explains how to effectively update the contents
of a React Fragment using state management and keyed fragments.
Updating Fragments via Parent State
Since React Fragments are lightweight wrappers that do not maintain their own state, the most common way to update their content is by updating the state of the parent component. When the parent component’s state changes, React automatically re-renders the component, updating the elements wrapped inside the Fragment.
import React, { useState } from 'react';
function UserProfile() {
const [userName, setUserName] = useState('Guest');
return (
<>
<h1>Welcome, {userName}</h1>
<button onClick={() => setUserName('Jane Doe')}>
Log In
</button>
</>
);
}In this example, updating the userName state triggers a
re-render, safely updating the text node inside the shorthand fragment
(<>...</>).
Forcing Re-renders Using Keyed Fragments
There are scenarios where you need to force a React Fragment and its
children to completely unmount and remount, resetting any local state of
the child components. To do this, you must use the standard
<React.Fragment> syntax instead of the shorthand
<></>, as the shorthand syntax does not support
attributes or keys.
By assigning a dynamic key prop to the Fragment, you can
force React to treat it as a brand-new element whenever the key
changes.
import React, { useState } from 'react';
function ProductList() {
const [listId, setListId] = useState(1);
const items = [
{ id: 1, name: 'Item A' },
{ id: 2, name: 'Item B' }
];
return (
<div>
<button onClick={() => setListId(prev => prev + 1)}>
Refresh List View
</button>
{/* Changing the key forces the Fragment to unmount and remount */}
<React.Fragment key={listId}>
{items.map(item => (
<p key={item.id}>{item.name}</p>
))}
</React.Fragment>
</div>
);
}Key Takeaways
- Shorthand Syntax
(
<>...</>): Use this for basic grouping when no updates or keys are required. - Explicit Syntax
(
<React.Fragment>): Use this when you need to pass akeyprop to the Fragment, which is essential when rendering lists or forcing component remounts. - State Updates: Always manage the data driving the Fragment’s children within the parent component’s state to ensure UI updates are handled correctly by React’s virtual DOM.