The useMemo hook helps your React app remember a value so it doesn't have to recalculate it every time. This makes your app faster and smoother.
useMemo hook in React
const memoizedValue = useMemo(() => { // calculation or function return result; }, [dependencies]);
The first argument is a function that returns the value you want to remember.
The second argument is an array of dependencies. The value recalculates only if these change.
number only when number changes.const doubled = useMemo(() => number * 2, [number]);
list only when list changes.const sortedList = useMemo(() => [...list].sort(), [list]);const config = useMemo(() => ({ theme: 'dark' }), []);
This example shows a component that calculates double of a number. The calculation logs a message only when the number changes. Clicking 'Toggle Other' does not recalculate because useMemo remembers the value.
import React, { useState, useMemo } from 'react'; function ExpensiveCalculation({ number }) { const doubled = useMemo(() => { console.log('Calculating double...'); return number * 2; }, [number]); return <div>Double: {doubled}</div>; } export default function App() { const [count, setCount] = useState(0); const [other, setOther] = useState(false); return ( <main> <h1>useMemo Example</h1> <button onClick={() => setCount(c => c + 1)}>Increase Count</button> <button onClick={() => setOther(o => !o)}>Toggle Other</button> <p>Count: {count}</p> <p>Other: {other.toString()}</p> <ExpensiveCalculation number={count} /> </main> ); }
Don't use useMemo to fix bugs or for every value. Use it only when performance matters.
Remember to include all variables used inside the function in the dependencies array.
Logging inside useMemo helps see when it recalculates.
useMemo remembers a value between renders to avoid repeating work.
It recalculates only when dependencies change.
Use it to speed up slow calculations or keep stable references.