📖 Scenario: You are building a simple React app that calculates the sum of numbers in a list. The list can be changed by the user. To avoid recalculating the sum every time the component re-renders, you will use the useMemo hook.
🎯 Goal: Build a React functional component that uses useMemo to efficiently calculate and display the sum of a list of numbers.
📋 What You'll Learn
Create a list of numbers as initial data
Add a state variable to hold the list
Use the useMemo hook to calculate the sum of the numbers
Display the sum in the component
💡 Why This Matters
🌍 Real World
Using useMemo helps improve performance in React apps by avoiding unnecessary recalculations, especially when working with large data or expensive computations.
💼 Career
Understanding useMemo is important for React developers to write efficient and responsive user interfaces.
Progress0 / 4 steps
1
Create the initial list of numbers
Create a constant array called numbers with these exact values: [10, 20, 30, 40, 50].
React
Hint
Use const numbers = [10, 20, 30, 40, 50]; to create the array.
2
Add state to hold the numbers list
Import useState from React and create a state variable called list with the initial value set to numbers. Also create the setter function called setList.
React
Hint
Use const [list, setList] = useState(numbers); inside your component.
3
Use useMemo to calculate the sum
Import useMemo from React and create a constant called sum that uses useMemo to calculate the sum of all numbers in list. The calculation should only run when list changes.
React
Hint
Use const sum = useMemo(() => list.reduce((acc, num) => acc + num, 0), [list]);
4
Display the sum in the component
Return a JSX element that shows a <div> with the text Total Sum: followed by the sum value. Close the function with a closing brace.
React
Hint
Use return <div>Total Sum: {sum}</div>; to show the sum.
Practice
(1/5)
1. What is the main purpose of the useMemo hook in React?
easy
A. To remember a computed value between renders and recalculate only if dependencies change
B. To fetch data from an API asynchronously
C. To manage component state
D. To handle side effects like subscriptions or timers
Solution
Step 1: Understand what useMemo does
useMemo stores 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 like useEffect or useState, not useMemo.
Final Answer:
To remember a computed value between renders and recalculate only if dependencies change -> Option A
Quick Check:
useMemo = memoize value [OK]
Hint: Remember: useMemo caches values, not effects or state [OK]
Common Mistakes:
Confusing useMemo with useEffect
Thinking useMemo manages state
Assuming useMemo runs every render
2. Which of the following is the correct syntax to use useMemo in a React functional component?
easy
A. const memoizedValue = useMemo(computeValue(), []);
B. const memoizedValue = useMemo(computeValue, dependencies);
C. const memoizedValue = useMemo(() => computeValue(), [dependencies]);
D. const memoizedValue = useMemo(() => computeValue, [dependencies]);
Solution
Step 1: Recall correct useMemo syntax
useMemo takes 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 C
Quick Check:
useMemo syntax = arrow function + deps array [OK]
Hint: useMemo needs a function and dependencies array [OK]
Common Mistakes:
Calling the compute function immediately inside useMemo
Passing dependencies without an array
Passing function reference without wrapping in arrow function
The double value is computed as count * 2, and recalculated only when count changes.
Step 2: Substitute count value
When count is 3, double becomes 3 * 2 = 6.
Final Answer:
6 -> Option A
Quick Check:
count 3 times 2 = 6 [OK]
Hint: Multiply count by 2 inside useMemo [OK]
Common Mistakes:
Confusing count with double
Ignoring dependency array effect
Assuming useMemo returns a function
4. Identify the problem in this code using useMemo:
const memoizedValue = useMemo(() => expensiveCalc(), []);
// Later in code
const result = memoizedValue();
medium
A. Dependency array is missing, so useMemo recalculates every render
B. Calling memoizedValue as a function causes an error because it stores a value, not a function
C. expensiveCalc is not defined
D. useMemo should not be used with functions
Solution
Step 1: Understand what useMemo returns
useMemo returns the memoized value, not a function, so calling it as a function causes an error.
Step 2: Analyze the code usage
The code calls memoizedValue(), but memoizedValue is the result of expensiveCalc(), not a function.
Final Answer:
Calling memoizedValue as a function causes an error because it stores a value, not a function -> Option B
Quick Check:
useMemo returns value, not callable function [OK]
Hint: useMemo returns value, don't call it like a function [OK]
Common Mistakes:
Calling the memoized value as a function
Forgetting to pass dependencies
Confusing useMemo with useCallback
5. You have a component that filters a large list of users by a search term. Which use of useMemo best improves performance by avoiding unnecessary recalculations?
hard
A. const filteredUsers = users.filter(u => u.name.includes(searchTerm));
B. const filteredUsers = useMemo(() => users.filter(u => u.name.includes(searchTerm)), []);
C. const filteredUsers = useMemo(() => users.filter(u => u.name.includes(searchTerm)));