Mastering React’s useMemo Hook: A Comprehensive Guide with Examples

Love Trivedi
ZestGeek
Published in
3 min readAug 6, 2024

React is a powerful library for building user interfaces, and its hooks API has revolutionized the way developers write functional components. Among these hooks, useMemo stands out as a tool for optimizing performance. This article will delve into the useMemo hook, explaining its use cases and providing practical coding examples to demonstrate its effectiveness.

What is useMemo?

useMemo is a hook that memoizes the result of a calculation, recomputing it only when its dependencies change. This helps prevent expensive computations on every render, enhancing the performance of your application.

Syntax

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
  • computeExpensiveValue: The function whose result you want to memoize.
  • [a, b]: Dependencies array. useMemo will only recompute the memoized value when one of these dependencies changes.

When to Use useMemo

  • Expensive Computations: When a function performs complex calculations or processes large datasets.
  • Referential Equality: When you want to maintain the same reference for an object or array between renders to avoid unnecessary re-renders of child components.

Real-Life Coding Examples

Example 1: Expensive Calculation

Suppose you have a component that performs a costly calculation based on two input values:

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

function ExpensiveCalculationComponent() {
const [a, setA] = useState(1);
const [b, setB] = useState(1);

const expensiveCalculation = (num1, num2) => {
console.log('Calculating...');
return num1 * num2;
};

const result = useMemo(() => expensiveCalculation(a, b), [a, b]);

return (
<div>
<input type="number" value={a} onChange={(e) => setA(parseInt(e.target.value))} />
<input type="number" value={b} onChange={(e) => setB(parseInt(e.target.value))} />
<p>Result: {result}</p>
</div>
);
}

export default ExpensiveCalculationComponent;

In this example, the expensiveCalculation function is only called when either a or b changes, saving unnecessary computations on every render.

Example 2: Referential Equality

Consider a scenario where you pass an array as a prop to a child component. Without useMemo, the array would be re-created on every render, causing the child component to re-render unnecessarily.

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

function ChildComponent({ items }) {
console.log('ChildComponent re-rendered');
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
}

function ParentComponent() {
const [count, setCount] = useState(0);

const items = useMemo(() => ['Item 1', 'Item 2', 'Item 3'], []);

return (
<div>
<button onClick={() => setCount(count + 1)}>Increment</button>
<ChildComponent items={items} />
</div>
);
}

export default ParentComponent;

Here, useMemo ensures that the items array maintains the same reference between renders, preventing ChildComponent from re-rendering when count changes.

Example 3: Filtering a Large Dataset

If you have a large dataset that needs filtering based on user input, useMemo can help optimize performance:

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

const data = [...Array(10000).keys()]; // Array of numbers from 0 to 9999

function LargeDatasetComponent() {
const [query, setQuery] = useState('');

const filteredData = useMemo(() => {
console.log('Filtering data...');
return data.filter((item) => item.toString().includes(query));
}, [query]);

return (
<div>
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search..."
/>
<ul>
{filteredData.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
</div>
);
}

export default LargeDatasetComponent;

The filteredData is only recomputed when the query changes, improving the performance when dealing with a large dataset.

Conclusion

useMemo is a powerful hook for optimizing performance in React applications. By memoizing the results of expensive computations and ensuring referential equality, you can prevent unnecessary re-renders and improve the efficiency of your components. The examples provided here demonstrate practical scenarios where useMemo can be effectively utilized, helping you write more performant React applications.

About Zestgeek Solutions Private Limited

At Zestgeek Solutions Private Limited, we specialize in delivering cutting-edge web and mobile app development services. With over 50 in-house developers proficient in the latest programming technologies, we are equipped to handle projects of any scale and complexity. Our expertise in integrating AI and automation into development processes ensures that our clients receive top-quality, scalable, and maintainable solutions.

Whether you need a robust web application or a dynamic mobile app, Zestgeek Solutions is committed to bringing your vision to life. Partner with us to leverage our technical prowess and innovative approach, and let’s build the future together.

--

--

Love Trivedi
ZestGeek

Full Stack Developer | Problem Solver | Knowledge Share, 🚀 Expertise: JavaScript enthusiast specializing in ReactJS, Angular, and Node.js.