Filter a list from the search text on every render instead of keeping a second copy in state.
React · intermediate · 6 min · 20 steps · free
import { useState } from 'react';
const FRUITS = ['Apple', 'Apricot', 'Banana', 'Cherry'];
export default function FruitSearch() {
const [query, setQuery] = useState('');
const visible = FRUITS.filter((f) => f.toLowerCase().startsWith(query));
return (
<div>
<input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search" />
<p>
{visible.length} of {FRUITS.length}: {visible.join(', ')}
</p>
</div>
);
}<FruitSearch> for the first time: it calls the FruitSearch function.useState runs for the first time, so React stores the starting value for query and returns it: "".f = "Apple", the callback returns true.f = "Apricot", the callback returns true.f = "Banana", the callback returns true.f = "Cherry", the callback returns true.visible holds every fruit while the query is empty.FruitSearch returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.onChange handler.setQuery(e.target.value) does not change query right away: React queues the update and will render again. In this call query is still "".<FruitSearch> again (render 2): it calls FruitSearch once more, from the top.useState returns the value React has kept for query: "ap". The starting value is only used on the first render.f = "Apricot", the callback returns true.f = "Cherry", the callback returns false.visible = ["Apple", "Apricot"], worked out fresh in this render.FruitSearch returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.Answer: Calculation
Answer: It can get out of sync with query
← Keys and Component Identity · memo: Skipping a Re-render →