0
0
Reactframework~30 mins

useMemo hook in React - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the useMemo Hook in React
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use return <div>Total Sum: {sum}</div>; to show the sum.