Tutorials Courses Interview Prep (100 Q&A) AI Tools (50) Developer Tools (50) Tracks Pricing Plans Blog & Articles Contact Us
Advanced React 19 & Production Patterns 20 mins read Free Lesson

Performance Optimization: useMemo, useCallback & memo

Prevent unnecessary re-renders, optimize expensive computations, and maintain referential stability.

Referential Equality & Memoization

import { useState, useMemo, useCallback, memo } from 'react';

// Memoized child component only re-renders when props change by shallow comparison
const ExpensiveChart = memo(function ExpensiveChart({ data, onSelect }) {
    return <div onClick={() => onSelect(data.id)}>Rendered Chart: {data.value}</div>;
});

export function Dashboard() {
    const [count, setCount] = useState(0);
    const [items] = useState([{ id: 1, value: 450 }, { id: 2, value: 890 }]);

    const total = useMemo(() => items.reduce((acc, i) => acc + i.value, 0), [items]);
    const handleSelect = useCallback((id) => console.log('Selected:', id), []);

    return (
        <div>
            <h3>Total Score: {total}</h3>
            {items.map(item => <ExpensiveChart key={item.id} data={item} onSelect={handleSelect} />)}
            <button onClick={() => setCount(c => c + 1)}>Counter: {count}</button>
        </div>
    );
}