What is useMemo in React: Explanation and Example
useMemo is a React hook that remembers the result of a function so it doesn’t have to run again unless its inputs change. It helps speed up your app by avoiding unnecessary recalculations during rendering.How It Works
Imagine you have a recipe that takes a long time to prepare. Instead of making it from scratch every time you want to eat, you make it once and save it in the fridge. When you want it again, you just take it out instead of cooking again. useMemo works similarly in React. It remembers the result of a calculation or function and only recalculates it if the ingredients (inputs) change.
This means React can skip expensive work during rendering if nothing important has changed. It keeps your app fast and smooth, especially when dealing with heavy calculations or large lists.
Example
This example shows how useMemo caches a slow calculation so it only runs when the input number changes.
import React, { useState, useMemo } from 'react'; function SlowSquare({ number }) { const squared = useMemo(() => { console.log('Calculating square...'); let result = 0; for (let i = 0; i < 1000000000; i++) { // The loop is just to simulate a slow calculation } result = number * number; return result; }, [number]); return <div>Square of {number} is {squared}</div>; } export default function App() { const [num, setNum] = useState(2); const [count, setCount] = useState(0); return ( <div> <SlowSquare number={num} /> <button onClick={() => setNum(num + 1)}>Increase Number</button> <button onClick={() => setCount(count + 1)}>Re-render</button> <p>Re-render count: {count}</p> </div> ); }
When to Use
Use useMemo when you have a calculation or operation that takes a lot of time or resources and you want to avoid doing it on every render. It is helpful when:
- You compute derived data from props or state that is expensive.
- You want to prevent unnecessary recalculations when unrelated parts of the component update.
- You want to optimize rendering performance in large lists or complex UI.
However, don’t use it everywhere. If the calculation is cheap, useMemo adds extra complexity without benefits.
Key Points
- useMemo caches a value between renders based on dependencies.
- It only recalculates when dependencies change.
- Helps optimize performance by skipping expensive work.
- Not a tool for all cases; use only when needed.
- Works well with pure functions and stable inputs.