The useMemo Hook is a built-in React Hook that helps optimize performance by memoizing the result of a computation and reusing it unless its dependencies change. This prevents expensive computations from being re-executed unnecessarily during component re-renders.
Syntax
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
- The first argument is a function that returns the computed value.
- The second argument is an array of dependencies. When any of these dependencies change, the function gets re-evaluated.
Let's now see some of the Practical Applications of useMemo
1. Optimizing Expensive Calculations
Let’s take an example where we have an expensive computation that should not be recalculated on every render.
JavaScript
import React, { useState, useMemo } from "react";
function App() {
const [number, setNumber] = useState(0);
const squaredNum = useMemo(() => squareNum(number), [number]);
const [counter, setCounter] = useState(0);
const onChangeHandler = (e) => {
setNumber(e.target.value);
};
const counterHander = () => {
setCounter(counter + 1);
};
return (
<div className="App">
<h1>Welcome to Geeksforgeeks</h1>
<input
type="number"
placeholder="Enter a number"
value={number}
onChange={onChangeHandler}
></input>
<div>OUTPUT: {squaredNum}</div>
<button onClick={counterHander}>Counter ++</button>
<div>Counter : {counter}</div>
</div>
);
}
function squareNum(number) {
console.log("Squaring will be done!");
return Math.pow(number, 2);
}
export default App;
Output
In this example
- useState manages number (user input) and counter (button clicks).
- useMemo caches squareNum(number), recalculating only when number changes.
- The input field updates the number state when changed.
- Clicking "Counter ++" increases the counter state.
- The component displays the input, memoized squared value, and counter.
2. Preventing Unnecessary Re-renders
Sometimes, passing objects or arrays as props to child components can trigger unnecessary re-renders due to reference changes. useMemo can help stabilize such values.
JavaScript
import React, { useState, useMemo } from "react";
function Child({ userInfo }) {
console.log("Child component rendered");
return <p>User: {userInfo.name}</p>;
}
function Parent() {
const [count, setCount] = useState(0);
const userInfo = useMemo(() => ({ name: "GeeksforGeeks" }), []);
return (
<div>
<p>Count: {count}</p>
<Child userInfo={userInfo} />
<button onClick={() => setCount(count + 1)}>Increment Count</button>
</div>
);
}
export default Parent;
Output
In this example
- React, useState, and useMemo are imported for state management and optimization.
- ChildComponent displays userInfo.name and logs renders.
- ParentComponent memoizes userInfo to prevent re-creation.
- Clicking the button updates count, re-rendering ParentComponent.
- ParentComponent displays count, ChildComponent, and the button.
When to Use useMemo?
You should use useMemo when
- You have expensive calculations that do not need to be re-executed unless certain dependencies change.
- You are dealing with large data sets and need to optimize performance.
- You want to prevent unnecessary re-renders of child components by ensuring stable references.
However, avoid overusing useMemo as it can add complexity and memory overhead. Use it only when necessary.
Performance Optimization Using useMemo
Using useMemo correctly can significantly enhance the performance of React applications. However, improper usage may lead to unnecessary memory usage and increased complexity. Here are some key considerations:
- Avoid using useMemo for trivial calculations: If the computation is lightweight, memoization may introduce unnecessary complexity.
- Use it for expensive calculations: Tasks such as filtering large datasets or performing intensive calculations can benefit from useMemo.
- Stabilize object and array references: When passing objects or arrays to child components, useMemo helps maintain the same reference and prevents unnecessary re-renders.
- Measure before optimizing: Always analyze your app’s performance using React DevTools or profiling tools before introducing useMemo.
Key Takeaways
- Performance optimization: useMemo helps optimize expensive calculations.
- Prevents unnecessary re-renders: Helps in stabilizing reference values passed as props.
- Use it wisely: Overuse of useMemo can lead to unnecessary complexity.
Similar Reads
ReactJS useId Hook React useId Hook is introduced for the ReactJS versions above 18. This hook generates unique IDs i.e, returns a string that is stable across both the server and the client sides. Prerequisite: Introduction and installation of ReactJSReact Hooks Syntax: const id = useId() Creating React Application:
3 min read
ReactJS useEffect Hook The useEffect hook is one of the most commonly used hooks in ReactJS used to handle side effects in functional components. Before hooks, these kinds of tasks were only possible in class components through lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.What is
4 min read
ReactJS useParams Hook In ReactJS, when building single-page applications (SPAs) with dynamic routing, you often need to access dynamic data from the URL. For example, in a blog application, the URL will change depending on the post being viewed, like /post/:id. The useParams hook, provided by the react-router-dom package
3 min read
ReactJS useContext Hook In React Applications, sometimes managing state across deeply nested components can become very difficult. The useContext hook offers a simple and efficient solution to share state between components without the need for prop drilling.What is useContext Hook?The useContext hook in React allows compo
5 min read
React useState Hook The useState hook is a function that allows you to add state to a functional component. It is an alternative to the useReducer hook that is preferred when we require the basic update. useState Hooks are used to add the state variables in the components. For using the useState hook we have to import
5 min read
ReactJs useDebugValue Hook React useDebugValue Hook is introduced for the ReactJs versions above 18. React useDebugValue Hook helps developers debug custom hooks in React Developer Tools by adding additional information and labels to those hooks. Prerequisite:ReactJSReact Developer ToolsReact HooksReact Custom HooksApproach:T
2 min read
ReactJS useLayoutEffect Hook The React JS useLayoutEffect works similarly to useEffect but rather works asynchronously like the useEffect hook, it fires synchronously after all DOM loading is done loading. This is useful for synchronously re-rendering the DOM and also to read the layout from the DOM. But to prevent blocking the
2 min read
React-Router Hooks React-Router is a popular React library that is heavily used for client-side routing and offers single-page routing. It provides various Component APIs( like Route, Link, Switch, etc.) that you can use in your React application to render different components based on the URL pathnames on a single pa
11 min read
React Hooks ReactJS Hooks are one of the most powerful features of React, introduced in version 16.8. They allow developers to use state and other React features without writing a class component. Hooks simplify the code, make it more readable, and offer a more functional approach to React development. With hoo
10 min read
State Hooks in React State Hooks, introduced in React 16.8, revolutionized how developers manage state in functional components. Before State Hooks, state management was primarily confined to class components using the setState method. State Hooks, such as useState, enable functional components to manage local state eff
3 min read