ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

React.js Tutorial• 7 min read

Performance: useMemo, useCallback & React.memo

Memoizing expensive calculations, stable function references, and preventing re-renders

By default, when a parent component re-renders, all child components re-render. useMemo, useCallback, and React.memo skip unnecessary recalculations and render cycles.

The Performance Optimization Trio

useMemo(() => computeHeavy(data), [data]): Caches the RESULT of an expensive mathematical computation between renders.

useCallback((id) => handleClick(id), []): Caches a FUNCTION REFERENCE between renders so child components receiving the callback as a prop don't re-render needlessly.

React.memo(Component): Higher-order component that skips re-rendering if incoming props have not shallowly changed.

useMemo and useCallback Example
function AnalyticsDashboard({ rawData, onExport }) {
  // 1. Memoize expensive calculation
  const totalRevenue = React.useMemo(() => {
    console.log("Calculating revenue across 100,000 transactions...");
    return rawData.reduce((acc, item) => acc + item.amount, 0);
  }, [rawData]);

  // 2. Stable function callback reference
  const handleExportCSV = React.useCallback(() => {
    onExport(totalRevenue);
  }, [totalRevenue, onExport]);

  return (
    <div>
      <h3>Total Revenue: ${totalRevenue.toLocaleString()}</h3>
      <button onClick={handleExportCSV}>Export Report</button>
    </div>
  );
}
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What is the primary difference between `useMemo` and `useCallback` in React?