Blog>
Snippets

Optimizing List Performance with useMemo and useCallback

Illustrate the use of `useMemo` and `useCallback` hooks to optimize the rendering performance of items in a virtualized list, highlighting their impact on reducing unnecessary renders.
const ListItem = React.memo(({ itemData }) => {
  return <div>{itemData.name}</div>;
});
Wraps each list item in a React.memo to ensure it only re-renders when its props have changed, minimizing unnecessary renders.
const generateItemData = useCallback((data) => {
  // performs heavy calculations or processing
  return processData(data);
}, []);
Uses useCallback to memoize a complex function, ensuring it's only recreated if its dependencies change. In this case, it has no dependencies and will not be recreated on every render.
const itemListMemoized = useMemo(() => items.map(item => generateItemData(item)), [items, generateItemData]);
Uses useMemo to memoize the transformation of items. This ensures the processing is only re-executed when 'items' or 'generateItemData' change.