useMemo in ReactJS
2 min read 4 days ago
useMemo
is a hook in React that allows you to memoize expensive computations so that they are only re-computed when their dependencies change. This can help improve performance by avoiding unnecessary calculations on every render.
Here’s a step-by-step guide on how to use useMemo
:
Basic Usage
Example: Memoizing a Computed Value
import React, { useState, useMemo } from 'react';
const ExpensiveCalculationComponent = () => {
const [count, setCount] = useState(0);
const [text, setText] = useState("");
const expensiveCalculation = (num) => {
console.log("Calculating...");
for (let i = 0; i < 1000000000; i++) {} // Simulating a heavy computation
return num * 2;
};
const memoizedValue = useMemo(() => expensiveCalculation(count), [count]);
return (
<div>
<h1>Count: {count}</h1>
<h1>Memoized Value: {memoizedValue}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
<input
type="text"
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="Type something..."
/>
</div>
);
};
export default ExpensiveCalculationComponent;
n this example:
useMemo
is used to memoize the result ofexpensiveCalculation(count)
.- The calculation is only re-run when the
count
changes, not when thetext
changes.
When to Use useMemo
Use useMemo
when:
- You have expensive calculations that are causing performance issues.
- You want to avoid recomputing a value unless its dependencies have changed.
Example: Filtering a Large List
import React, { useState, useMemo } from 'react';
const FilteredList = ({ items }) => {
const [filter, setFilter] = useState("");
const filteredItems = useMemo(() => {
console.log("Filtering items...");
return items.filter(item =>
item.toLowerCase().includes(filter.toLowerCase())
);
}, [filter, items]);
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>
);
};
export default FilteredList;
In this example:
useMemo
is used to memoize the filtered list.- The filtering function runs only when
filter
oritems
change.
Summary
- Performance optimization:
useMemo
helps prevent expensive calculations from being run on every render. - Dependency array: The second argument to
useMemo
is a dependency array that determines when the memoized value should be recomputed. - Use cases: Filtering large lists, complex calculations, and other CPU-intensive operations.
Using useMemo
can significantly enhance performance in applications with complex computations or large datasets. However, it should be used judiciously, as premature optimization can lead to unnecessary complexity.