React › Performance (memo/useMemo)
What is a simple real world example of when useMemo actually helps a React app?
BeginnerAnswer
Imagine a component that sorts a very large list of items every time it renders. If the list itself has not changed, sorting it again on every render wastes time. Wrapping that sort operation in useMemo means React only redoes the sorting when the actual list changes, saving unnecessary work on unrelated re renders.
function SortedList({ items }) {
const sortedItems = useMemo(
() => [...items].sort((a, b) => a.name.localeCompare(b.name)),
[items]
);
return <ul>{sortedItems.map((item) => <li key={item.id}>{item.name}</li>)}</ul>;
}Real-world example A contact list app avoids re sorting thousands of contacts every time an unrelated part of the screen updates, since the sorting work is wrapped in useMemo and only runs again when the actual contact list changes.