useMemo for Complex Object Transformations
You'll learn how to prevent React from unnecessarily repeating expensive object transformations on every render by caching their results with useMemo.
What Are Complex Object Transformations?
Sometimes you receive raw data—maybe from props or API responses—that needs heavy processing before your component can use it. This might include:
- Parsing nested JSON structures into flattened maps
- Transforming an array of items into a keyed lookup object
- Computing derived state by merging multiple data sources
- Filtering and reshaping data structures
Without memoization, React recalculates these transformations on every single render, even when the source data hasn't changed.
The Problem
function UserDashboard({ users, roles }) {
// ⚠️ Runs on EVERY render, even if users/roles are unchanged
const usersByRole = users.reduce((acc, user) => {
const role = roles[user.roleId];
if (!acc[role.name]) acc[role.name] = [];
acc[role.name].push(user);
return acc;
}, {});
return <RoleList roleGroups={usersByRole} />;
}
The Solution
Wrap the transformation in useMemo, listing the source data in the dependency array:
function UserDashboard({ users, roles }) {
const usersByRole = useMemo(() => {
return users.reduce((acc, user) => {
const role = roles[user.roleId];
if (!acc[role.name]) acc[role.name] = [];
acc[role.name].push(user);
return acc;
}, {});
}, [users, roles]); // Only recalculate when these change
return <RoleList roleGroups={usersByRole} />;
}
Now React caches usersByRole and only recomputes it when users or roles actually change.
Key Takeaway: Use useMemo to cache complex object transformations—parsing, merging, or reshaping data structures—so they only run when their source data changes, not on every render.