Performance: The Slow List
Mission
Fix a laggy list by finding unnecessary re-renders and removing them with React.memo, useMemo and useCallback.
Tasks
- 1
Find the bottleneck: type in the input and watch the console. The whole list renders on every keystroke.
- 2
Extract the list item into a component called
ListItem. - 3
Wrap
ListIteminReact.memoso it only re-renders when its props change. - 4
Memoize the filtering with
useMemoso it only runs when the search term changes. - 5
Write
handleSelectwithuseCallbackso its reference stays stable between renders. - 6
Remove any
console.logyou added before you finish.
import React, { useState, useMemo, useCallback } from 'react'; import './styles.css'; // Imagine this list comes from a heavy API const slowItems = Array.from({ length: 500 }, (_, i) => "Item " + i); // 1. Create the ListItem component here and wrap it in React.memo export default function App() { const [search, setSearch] = useState(""); const [selected, setSelected] = useState(null); // 2. Optimize this filtering with useMemo const filtered = slowItems.filter(item => item.toLowerCase().includes(search.toLowerCase()) ); // 3. Create handleSelect with useCallback const handleSelect = (item) => { setSelected(item); }; return ( <div style={{ padding: '20px', fontFamily: 'sans-serif' }}> <h1>High-Performance List</h1> <p>Selected: {selected || 'None'}</p> <input type="text" placeholder="Type fast to feel the lag..." value={search} onChange={e => setSearch(e.target.value)} /> <ul> {filtered.map(item => ( <li key={item}> {item} </li> ))} </ul> </div> ); }
Requirements
0/6The item lives in its own ListItem component (not run yet)
ListItem is wrapped in memo() (not run yet)
The filtering runs inside useMemo with [search] (not run yet)
handleSelect is created with useCallback (not run yet)
ListItem receives no inline functions as props (not run yet)
No console.log left in the final code (not run yet)
AI mentor
Reviews only the files you changed, plus the checks you missed.
Run the checks first. They are free and instant.