Set your Publisher ID in src/config/ads.ts to display live ads.
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.
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>
);
}Set your Publisher ID in src/config/ads.ts to display live ads.
Test Yourself With Exercise
What is the primary difference between `useMemo` and `useCallback` in React?