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.
Practice
useMemo hook in React?Solution
Step 1: Understand what
useMemodoesuseMemostores a value and recalculates it only when its dependencies change, avoiding repeated work.Step 2: Compare with other hooks
Fetching data or managing state are done by other hooks likeuseEffectoruseState, notuseMemo.Final Answer:
To remember a computed value between renders and recalculate only if dependencies change -> Option AQuick Check:
useMemo = memoize value [OK]
- Confusing useMemo with useEffect
- Thinking useMemo manages state
- Assuming useMemo runs every render
useMemo in a React functional component?Solution
Step 1: Recall correct useMemo syntax
useMemotakes a function returning the value and an array of dependencies:useMemo(() => value, [deps]).Step 2: Analyze options
const memoizedValue = useMemo(() => computeValue(), [dependencies]); correctly uses an arrow function and dependency array. Others either call the function immediately or miss the arrow function.Final Answer:
const memoizedValue = useMemo(() => computeValue(), [dependencies]); -> Option CQuick Check:
useMemo syntax = arrow function + deps array [OK]
- Calling the compute function immediately inside useMemo
- Passing dependencies without an array
- Passing function reference without wrapping in arrow function
const [count, setCount] = useState(0);
const double = useMemo(() => count * 2, [count]);
return <div>{double}</div>;What will be displayed when
count is 3?Solution
Step 1: Understand the useMemo calculation
Thedoublevalue is computed ascount * 2, and recalculated only whencountchanges.Step 2: Substitute count value
Whencountis 3,doublebecomes 3 * 2 = 6.Final Answer:
6 -> Option AQuick Check:
count 3 times 2 = 6 [OK]
- Confusing count with double
- Ignoring dependency array effect
- Assuming useMemo returns a function
useMemo:const memoizedValue = useMemo(() => expensiveCalc(), []); // Later in code const result = memoizedValue();
Solution
Step 1: Understand what useMemo returns
useMemoreturns the memoized value, not a function, so calling it as a function causes an error.Step 2: Analyze the code usage
The code callsmemoizedValue(), butmemoizedValueis the result ofexpensiveCalc(), not a function.Final Answer:
Calling memoizedValue as a function causes an error because it stores a value, not a function -> Option BQuick Check:
useMemo returns value, not callable function [OK]
- Calling the memoized value as a function
- Forgetting to pass dependencies
- Confusing useMemo with useCallback
useMemo best improves performance by avoiding unnecessary recalculations?Solution
Step 1: Identify dependencies for filtering
The filtered list depends on bothusersandsearchTerm, so both must be in the dependency array.Step 2: Evaluate each option
const filteredUsers = useMemo(() => users.filter(u => u.name.includes(searchTerm)), [users, searchTerm]); correctly recalculates only whenusersorsearchTermchange. const filteredUsers = useMemo(() => users.filter(u => u.name.includes(searchTerm)), []); never recalculates after first render. const filteredUsers = useMemo(() => users.filter(u => u.name.includes(searchTerm))); misses dependencies array. const filteredUsers = users.filter(u => u.name.includes(searchTerm)); recalculates every render.Final Answer:
const filteredUsers = useMemo(() => users.filter(u => u.name.includes(searchTerm)), [users, searchTerm]); -> Option DQuick Check:
Include all dependencies in useMemo array [OK]
- Leaving dependency array empty when dependencies exist
- Omitting dependency array causing recalculation every render
- Not using useMemo and filtering every render
Ready to prove it?
Pass the test and this pattern moves unknown
