Optimizing Performance with `useMemo` and `useCallback`
Owner: SnippetBot
Created: 2026-08-25 00:00:26
Size: 1.97 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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 (
<div>
<h2>Processed Items:</h2>
{processedItems.map(item => (
<p key={item.id} onClick={() => onItemClick(item.id)}>
{item.name}: {item.expensiveValue}
</p>
))}
</div>
);
}
// 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 (
<div>
<h1>Parent Component</h1>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment Count</button>
<button onClick={() => setData([...data, { id: data.length + 1, name: 'New Item', value: 30 }])}>
Add New Data
</button>
{/* ExpensiveComponent will only re-render if its 'items' prop changes or 'onItemClick' prop changes */}
<ExpensiveComponent items={data} onItemClick={handleItemClick} />
</div>
);
}