javascript / intermediate
Snippet
Optimizing Performance with useMemo
The useMemo hook returns a memoized value. It only recomputes the memoized value when one of the dependencies has changed, preventing expensive calculations on every render.
snippet.js
1
2
3
4
5
6
7
8
9
10
const MemoizedComponent = ({ data }) => {const processedData = useMemo(() => {return data.map(item => ({...item,calculatedValue: complexCalculation(item.value)}));}, [data]);return <div>{processedData.length} items ready</div>;};
react
Breakdown
1
useMemo(() => { ... }, [data])
The first argument is the function that returns the value, the second is the dependency array.