Example: Filtering a List
You'll learn how to filter a list based on search input without reaching for useState or useEffect.
The Scenario
You have a list of items (products, users, todos) and a search box. As the user types, you want to show only matching items. The temptation is to store the filtered list in separate state and update it in a useEffect whenever the search term changes.
The Right Way: Compute During Render
Instead of maintaining two pieces of state (the search term and the filtered results), keep only the search term in state. The filtered list is derived data—compute it directly during render:
function ProductList({ products }) {
const [searchTerm, setSearchTerm] = useState('');
// Compute filtered list directly during render
const filteredProducts = products.filter(product =>
product.name.toLowerCase().includes(searchTerm.toLowerCase())
);
return (
<div>
<input
value={searchTerm}
onChange={e => setSearchTerm(e.target.value)}
/>
<ul>
{filteredProducts.map(product => (
<li key={product.id}>{product.name}</li>
))}
</ul>
</div>
);
}
Why This Works
Every time searchTerm or products changes, the component re-renders. The .filter() runs fresh with the latest values. No synchronization bugs, no double renders, no stale closures. The filtered list is always correct because it's computed from the current data.
The Wrong Pattern (Don't Do This)
// ❌ Unnecessary complexity
const [filtered, setFiltered] = useState(products);
useEffect(() => {
setFiltered(products.filter(/* ... */));
}, [searchTerm, products]);
This causes two renders: one from the search term update, another from the effect setting filtered state.
Key Takeaway: When filtering a list based on user input, compute the filtered array directly during render—it's fast, simple, and always in sync with your data.