import React, { useState, useMemo, useCallback } from 'react'; // A component that simulates heavy computation function ExpensiveComponent({ items, onItemClick }) { // useMemo to memoize the result of a heavy computation // This computation will only re-run if 'items' dependency changes const processedItems = useMemo(() => { console.log('Performing heavy computation...'); // Simulate a time-consuming calculation return items.map(item => ({ ...item, expensiveValue: item.value * 2 + Math.random() // Placeholder for complex logic })); }, [items]); return (

Processed Items:

{processedItems.map(item => (

onItemClick(item.id)}> {item.name}: {item.expensiveValue}

))}
); } // Parent component function ParentComponent() { const [count, setCount] = useState(0); const [data, setData] = useState([ { id: 1, name: 'Apple', value: 10 }, { id: 2, name: 'Banana', value: 20 }, ]); // useCallback to memoize a function. // This prevents the 'onItemClick' prop from changing on every re-render of ParentComponent, // which in turn prevents unnecessary re-renders of ExpensiveComponent (if it uses React.memo). const handleItemClick = useCallback((id) => { console.log(`Item with ID ${id} was clicked.`); // You could update state here related to the clicked item }, []); // No dependencies means this function instance is created once return (

Parent Component

Count: {count}

{/* ExpensiveComponent will only re-render if its 'items' prop changes or 'onItemClick' prop changes */}
); }