Nearby lessons
25 of 44⚛️ ReactJS – useMemo Hook
📌 What is useMemo?
What is useMemo in React?
The useMemo hook is used to optimize performance in React applications.
It memoizes the result of an expensive computation and only recalculates it when its dependencies change.
This prevents unnecessary recalculations during re-renders.
📌 Why useMemo?
useMemoimproves performance by caching results of functions.- It prevents expensive recalculations on every render.
- It only re-computes when dependencies change.
- It is useful when a function returns a computed value and re-rendering is frequent.
⚙️ Without useMemo
In the following example, the multiCount() function runs every time the component re-renders.
Even when we update item, which has nothing to do with multiCount(),
the function still executes unnecessarily.
React Playground
import React, { useState } from 'react'; function App() { const [counter, setCounter] = useState(0) const [item, setItem] = useState(10) function multiCount() { console.warn("multiCount"); return counter * 5; } return ( <> <h1>Without useMemo Hook in React</h1> <h2>Counter: {counter}</h2> <h2>Item: {item}</h2> <h2>{multiCount()}</h2> <button onClick={() => setCounter(counter + 1)}>Update Counter</button> <button onClick={() => setItem(item * 10)}>Update Item</button> </> ) } export default App;
⚙️ With useMemo
By using useMemo, the multiCount() function is only recalculated
when counter changes. Updating item will not trigger a recalculation.
React Playground
import React, { useMemo, useState } from 'react'; function App() { const [counter, setCounter] = useState(0) const [item, setItem] = useState(10) const multiCountMemo = useMemo(function multiCount() { console.warn("multiCount"); return counter * 5; }, [counter]) return ( <> <h1>With useMemo Hook in React</h1> <h2>Counter: {counter}</h2> <h2>Item: {item}</h2> <h2>{multiCountMemo}</h2> <button onClick={() => setCounter(counter + 1)}>Update Counter</button> <button onClick={() => setItem(item * 10)}>Update Item</button> </> ) } export default App;
🧮 Execution Flow of useMemo
- Component renders.
useMemochecks its dependency array.- If dependencies have changed, it recalculates and stores the new value.
- If dependencies have not changed, it reuses the cached value.
- The memoized value is then returned and used in the component.
🧠 Test Your Knowledge
4 QuestionsProgress: 0 / 4
Keep Going!React - Custom Hooks