React useMemo
import { useState } from 'react';
function ProductList({ products, query }) {
console.log('Sorting products...');
const sorted = [...products].sort((a, b) => a.price - b.price);
const visible = sorted.filter((p) =>
p.name.toLowerCase().includes(query.toLowerCase())
);
return (
<ul>
{visible.map((p) => (
<li key={p.id}>{p.name} - ${p.price}</li>
))}
</ul>
);
}
// Every keystroke in an unrelated input elsewhere in the app that
// causes ProductList to re-render also re-sorts and re-filters
// the entire product array from scratch.
const products = [
{ id: 1, name: 'Widget', price: 25 },
{ id: 2, name: 'Gadget', price: 15 },
{ id: 3, name: 'Gizmo', price: 40 },
];
export default function App() {
const [count, setCount] = useState(0);
return (
<div>
<button onClick={() => setCount(count + 1)}>
Re-render parent ({count})
</button>
<ProductList products={products} query="g" />
</div>
);
}