lennythedev

useMemo, useCallback and React.memo

React.memo

const Twicer = (props) => { 
	return <div>{props.val * 2}</div> 
}
const memoizedComponent = React.memo(Square)

Returns a memoized version of a functinal component, which only re-renders when props change.

✅ Use for stateless components with static or not-so-dynamic props

❌ Don’t overuse! If possible, move components up and pass them as props instead, as described here Optimize react re-renders

React.useMemo

Returns a memoized value, usually for expensively calculated ones.

const RenderSearchResult = ({term}) => {
	const memoizedResults = React.useMemo(() => expensiveSearch(term), [term])
	return <ul>results: {memoizedResults.map(r => <li key={r.id}>r.val</li>)}</ul>
}
const Blender = ({liquid, fruits}) => {
	useEffect(() => {
		expensiveBlender(liquid, fruits)
	}, [liquid, fruits])

	...
}

const App = () => {
	const liquid = { milk: '2 cups' }
	const fruits = ['🍌','🍓','🥝'];

	// ❌ object and array are not referentially stable
	// return <Blender liquid={liquid} fruits={fruits}>

	const memoLiquid = useMemo(() => liquid);
	const memoFruits = useMemo(() => fruits);

	return <Blender liquid={memoLiquid} fruits={fruits}>
}

✅ Use for computationally expensive calculations or maintaining referential equality for objects and arrays

❌ Don’t use for static values or non-expensive calculations. If static values, define them once outside the component instead. Examples given are contrived. Don’t follow

React.useCallback


lenmorld
Full-stack ramblings and journal about anything web