Skip to main content

how to use useMemo hook in react with example

ยท 2 min read
Parth Maheta

The useMemo hook is a React hook that is used to memoize the result of a function, preventing unnecessary recalculations and improving performance. It's particularly useful when dealing with expensive computations or when you want to optimize the rendering of a component.

Here's a basic explanation of how to use the useMemo hook:

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

const ExpensiveComponent = ({ data }) => {
// Using useState to store a counter value
const [counter, setCounter] = useState(0);

// Using useMemo to memoize the result of a function
const expensiveResult = useMemo(() => {
console.log('Recalculating expensive result...');
// Simulating an expensive computation
return data * counter;
}, [data, counter]); // Dependency array - recompute when data or counter changes

return (
<p>Expensive Result: {expensiveResult}</p>
<button onClick={() => setCounter(prevCounter => prevCounter + 1)}>
Increment Counter

const App = () => {
// Example data
const data = 10;

return <ExpensiveComponent data={data} />;

export default App;

In this example:

  1. We have a component ExpensiveComponent that takes a data prop and contains a counter state using useState.

  2. The result of an expensive computation is memoized using the useMemo hook. The function inside useMemo will only be recomputed when the dependencies (data or counter) change.

  3. We log a message to the console to simulate an expensive computation, and you'll notice that the message is only logged when data or counter changes.

  4. We have a button that increments the counter, causing a re-render of the component. However, the expensive computation is only recalculated when necessary, thanks to useMemo.

This way, useMemo helps optimize the performance of your components by preventing unnecessary recalculations of expensive values. It's especially beneficial when dealing with complex computations or when you want to avoid unnecessary work during renders.