useMemo
– Memoizing in React
useMemo is a hook that helps you memoize the result of a function so React doesn’t have to recalculate it unless necessary.
In development, memoizing is an optimization technique where the result of a function is cached so it doesn’t have to be recalculated every time.
Syntax
const memoizedValue = useMemo(() => computeSomething(input), [input]);
- The first argument is a function that returns the value you want to memoize.
- The second is an array of dependencies — the memoized value will only update if one of these changes.
Example
Want to see what useMemo actually fixes — live in action?
Here's a snippet without it:
const filteredFruits = fruits.filter(fruit => {
console.log("Filtering...");
return fruit.includes(query);
});
Can you spot the issue?
Even though this works fine, there's a performance problem hiding underneath.
Every time any part of the component re-renders — even if it's unrelated to query — this filter() function runs again. That means:
- Unnecessary recalculations
- Wasted CPU cycles
- Slower performance in large lists
const filteredFruits = useMemo(() => {
console.log("Filtering...");
return fruits.filter(fruit => fruit.includes(query));
}, [query]);
Now, the filter() logic only runs when query changes.
No more repeated filtering on every render — just efficient, optimized behavior.
This small change makes a huge difference in performance, especially as your app grows.
- The filteredFruits value only updates when query changes.
- If you type in the input, it filters. But if you click other buttons in the app (not shown), it won't redo the filter.
Complete Code:
import React, { useState, useMemo } from 'react';
const fruits = ["Apple", "Banana", "Orange", "Mango", "Pineapple"];
function FruitSearch() {
const [query, setQuery] = useState("");
const filteredFruits = useMemo(() => {
console.log("Filtering fruits...");
return fruits.filter(fruit =>
fruit.toLowerCase().includes(query.toLowerCase())
);
}, [query]);
return (
setQuery(e.target.value)}
placeholder="Search fruits"
/>
{filteredFruits.map(fruit => {fruit})}
);
}
When Should You Use useMemo
?
- If you have heavy calculations.
- When rendering large lists that depend on props or state.
- When child components re-render unnecessarily due to props.
When You Should'nt?
Don’t just sprinkle useMemo
everywhere. It adds some overhead too. If your function is fast and your app is snappy — you probably don’t need it.