The useMemo
hook in React is used to memoize the result of a function. This helps optimize performance by caching the result of an expensive computation and reusing it when the inputs (dependencies) haven’t changed.
useMemo
is particularly useful when the computation is complex or when it prevents unnecessary re-rendering of child components.
Syntax:
useMemo(() => computeValue, [dependencies])
Basic Usage
useMemo
takes two arguments: a function that returns the computed value and an array of dependencies.
import React, { useState, useMemo } from 'react';
export default function ExampleComponent({ items }) {
const [filter, setFilter] = useState('');
const filteredItems = useMemo(() => {
return items.filter(item => item.includes(filter));
}, [items, filter]);
return (
<div>
<input
type="text"
value={filter}
onChange={(e) => setFilter(e.target.value)}
placeholder="Filter items"
/>
<ul>
{filteredItems.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
</div>
);
}
When to Use useMemo
Expensive Computations: Use useMemo
to memoize results of expensive computations that should only re-run when dependencies change.
Avoid Re-rendering: Use useMemo
to prevent unnecessary re-renders of child components by memoizing data or calculations passed as props.
Avoid Re-rendering of Child Components
import React, { useState, useMemo } from 'react';
function ChildComponent({ data }) {
console.log('ChildComponent rendered');
return <div>{data}</div>;
}
const MemoizedChild = React.memo(ChildComponent);
export default function ParentComponent() {
const [count, setCount] = useState(0);
const data = useMemo(() => {
return `Count is ${count}`;
}, [count]);
return (
<div>
<button onClick={() => setCount(count + 1)}>Increment</button>
<MemoizedChild data={data} />
</div>
);
}