What is the useMemo Hook in React?

Nadim Chowdhury - Oct 30 '23 - - Dev Community

useMemo is a hook in React that is used to memorize the output of a function. It helps in performance optimization by ensuring that expensive computations don't run unless necessary.

When you use useMemo, you provide it with a function and a list of dependencies. React will call that function and memorize its return value whenever the dependencies have changed between renders. If the dependencies haven't changed, React will skip the function call and reuse the memorized value from the previous render.

Here's a basic example:

import React, { useState, useMemo } from 'react';

function ExpensiveComputationComponent({ num }) {
const computeExpensiveValue = (n) => {
console.log('Computing...');
return n * n; // For demonstration. Replace this with any expensive computation.
};

const expensiveValue = useMemo(() => computeExpensiveValue(num), [num]);

return <div>Expensive value: {expensiveValue}</div>;
}

function App() {
const [number, setNumber] = useState(0);

return (
<div>
<button onClick={() => setNumber(number + 1)}>Increment</button>
<ExpensiveComputationComponent num={number} />
</div>
);
}

export default App;
Enter fullscreen mode Exit fullscreen mode

In the above example, computeExpensiveValue will only be called when num changes. On subsequent renders with the same num, the previously computed value will be used, and the expensive function won't be called again.

Keep in mind that useMemo should be used judiciously. Not every computation needs memoization, and overusing it can lead to unnecessary complexity and even reduce performance in some cases.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .