useMemo Hook
What are useMemo Hooks in React?
`useMemo`
is a React Hook that is used to memoize the result of a function so that it is only recomputed when its dependencies change. It is similar to useCallback Hook. The main difference is useMemo returns a memoized value and useCallback returns a memoized function.Tip : The useMemo Hook only runs when any of its dependencies update.
Syntax :
app/page.tsx
1const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
Practical Example :
app/page.tsx
1import React, { useMemo, useState } from 'react';
2const ExpensiveComponent = ({ data }) => {
3 // Calculate the sum of the array only when data changes
4 const sum = useMemo(() => {
5 console.log('Calculating sum...');
6 return data.reduce((acc, num) => acc + num, 0);
7 }, [data]);
8
9 return (
10 <div>
11 <p>Sum: {sum}</p>
12 </div>
13 );
14};
15
16const App = () => {
17 const [numbers, setNumbers] = useState([1, 2, 3, 4, 5]);
18
19 return (
20 <div>
21 <ExpensiveComponent data={numbers} />
22 <button onClick={() => setNumbers([...numbers, Math.random() * 10])}>
23 Add Number
24 </button>
25 </div>
26 );
27};
28
29export default App;
30
Explanation :
In this example, the
`totalCompletedTasks`
variable is memoized using `useMemo`
. The memoized value is only recalculated when the completedTasks array changes. This ensures that the calculation is optimized and doesn't occur unnecessarily on each render, improving the performance of the component.Tip : Caching return values like this is also known as memoization, which is why this Hook is called useMemo.