javascript / intermediate
Snippet
Optimizing Performance with useMemo
useMemo memoizes the result of a calculation, recomputing it only when one of its dependencies changes, which is vital for expensive filtering or sorting.
snippet.js
javascript
1
2
3
const filteredItems = useMemo(() => {return items.filter(item => item.value > threshold);}, [items, threshold]);
react
Breakdown
1
useMemo(() => { ... })
Tells React to remember the returned value between re-renders.
2
item.filter(...)
An array operation that could be expensive with thousands of items.
3
[items, threshold]
Only re-runs the filter if the source items or the filter criteria change.