How to use useMemo Hook in a Functional Component in React ?
Last Updated :
28 Apr, 2025
In React development, optimizing performance is crucial for delivering responsive and fast user experiences. One way to achieve this is by using the `useMemo` hook.
In this article, we'll explore what `useMemo` is, why it's beneficial, and how to use it effectively in functional components.
What is React useMemo?
`useMemo` is a React hook used for memoizing the result of expensive computations within functional components. It allows us to cache the value returned by a function and reuse it across renders, preventing unnecessary re-execution of the function.
Why do we use useMemo?
The primary purpose of `useMemo` is to optimize performance by avoiding redundant computations. When a component re-renders, any expressions within it, including function calls, are re-evaluated. If a function call involves expensive computations that don't need to be recalculated on every render, using `useMemo` can significantly improve performance by memoizing the result and only recomputing it when dependencies change.
React useMemo: How to Cache the Value of Expensive Utilities?
To use `useMemo`, we provide it with a function and an array of dependencies. The function is called during rendering, and its return value is cached until one of the dependencies changes.
Syntax of useMemo Hook:
const memoizedValue = useMemo(() => {
// Expensive computation
}, [dependency1, dependency2, ...]);
Example: In this example we will see an optimizing expensive utility functions with React useMemo Hook.
JavaScript
import React, { useState, useMemo, useEffect } from 'react';
const Memoized = () => {
const [count, setCount] = useState(0);
// Memoized function using useMemo
const expensiveOperation = useMemo(() => {
console.log('Creating expensive operation...');
return () => {
console.log('Performing expensive operation...');
let result = 0;
for (let i = 0; i < 1000000000; i++) {
result += i;
}
console.log('Expensive operation... Done');
return result;
};
}, []);
/*
Dependency array - empty array
indicates no dependencies
*/
// useEffect to log when the component is rendered
useEffect(() => {
console.log('Component is rendered');
});
/*
useEffect to simulate component
mount and execute expensive operation
*/
useEffect(() => {
console.log('Executing expensive operation...');
const result = expensiveOperation();
console.log('Expensive operation result:', result);
}, [expensiveOperation]);
return (
<div>
<button onClick={() =>
setCount(count + 1)}>
Increment Count
</button>
<p>Count: {count}</p>
</div>
);
};
export default Memoized;
Output:
OutputExplanation of Output:
- We create a component called Memoized that keeps track of a count using useState.
- We use useMemo to remember the result of a big math calculation. This calculation happens only once due to empty dependency array.
- useEffect is used to trigger expensiveOperation for the calculation inside it.
- Now, whenever the component re-renders, the calculation is only done again if the expensiveOperation function changes.
Conclusion:
`useMemo` is a powerful tool in React for optimizing performance by memoizing the result of expensive computations within functional components. By caching the value of these computations and reusing them across renders, we can significantly improve the efficiency and responsiveness of our applications. When dealing with computationally intensive tasks or complex calculations, consider using `useMemo` to optimize your functional components and enhance the overall user experience.
Similar Reads
How to use PropTypes in a Functional Component in React? PropTypes is a mechanism provided by React for type-checking props passed to components. It allows developers to specify the expected types of props (such as strings, numbers, arrays, objects, etc.) and whether they are required or optional. PropTypes helps catch bugs early by providing warnings in
2 min read
How to implement useContext Hook in a Functional Component ? In React, the useContext hook is used to consume values from a context. Context in React is a way to share values like themes, authentication status, or any other global state between components without explicitly passing the props through each level of the component tree. Syntax of useContext Hook:
2 min read
How to create a Functional Component in React? To create a functional component in React, you define a JavaScript function that returns JSX. These components are stateless and rely on props for data input. Functional components are concise, easy to read, and can utilize React Hooks for managing state and side effects, making them a fundamental b
2 min read
How can you use useCallback to memoize functions in a React component? In ReactJS, the useCallback hook is used to memoize functions so that they are not recreated on every render unless their dependencies change. This can be useful for optimizing performance in scenarios where we are passing functions down to child components as props, especially when those functions
2 min read
How to use componentWillMount() in React Hooks? The componentWillMount() method allows us to execute the React code synchronously when the component gets loaded or mounted in the DOM (Document Object Model). This method is called during the mounting phase of the React Life-cycle. You cannot use any of the existing React lifecycle methods like Com
2 min read