Avoid unnecessary re-renders with useMemo and useCallback.
React re-renders a component whenever its state or props change. Most of the time this is fine — but for expensive computations or stable function references, React provides two hooks.
Memoize the result of an expensive computation:
import { useMemo } from 'react'
function ProductList({ items, filter }: Props) {
const filtered = useMemo(
() => items.filter((item) => item.name.includes(filter)),
[items, filter]
);
return <ul>{filtered.map((i) => <li key={i.id}>{i.name}</li>)}</ul>;
}
useMemo recalculates only when [items, filter] changes.
Memoize a function reference so child components don't re-render unnecessarily:
import { useCallback } from 'react'
function Parent() {
const handleClick = useCallback(() => {
console.log('clicked');
}, []); // stable reference — recreated only when deps change
return <Child onClick={handleClick} />;
}
Don't optimize by default. Measure first with React DevTools Profiler. Apply useMemo / useCallback when:
Export a component ExpensiveList that:
items: number[] and multiplier: number as propsuseMemo to compute the doubled list: items.map(n => n * multiplier)<li> inside a <ul>export default function App(): JSX.Element { return <h1>Hello world</h1> }
No test results yet
Click Run Tests or press Ctrl+Enter