Optimize React performance by memoizing values and callbacks to prevent unnecessary re-renders.
useMemo from React at the top of your component file.import { useMemo } from "react";const total = useMemo(() => {
return items.reduce((sum, item) => sum + item.price, 0);
}, [items]);useMemo when the calculation is slow and frequent.useCallback from React at the top of your component file.import { useCallback } from "react";const handleClick = useCallback(() => {
console.log("clicked");
}, []);[] memoizes forever, never resetting.const value = useMemo(() => expensive(), []);const filtered = useMemo(() => filter(items, search), [items, search]);useMemo only for calculations that noticeably slow down rendering.useCallback when passing functions to optimized child components.React.memo() alongside useCallback for component memoization.const config = useMemo(() => ({
timeout: 5000, retries: 3
}), []);useCallback with useEffect to avoid infinite loops.const fetch = useCallback(async () => {
const res = await api.get();
setData(res);
}, []);useMemo to memoize complex derived state.useMemo caches the return value of a function, while useCallback caches the function itself. Use useMemo for expensive computations and useCallback when you need a stable function reference to pass as a prop or dependency.
Only memoize when the computation is genuinely expensive (e.g., filtering large arrays, complex math) and runs on frequent re-renders. For simple transformations, the overhead of memoization outweighs any benefit.
This is a stale closure caused by missing dependencies in the dependency array. Any variable from the component scope that the function references must be listed in the array, or the callback will capture its initial value indefinitely.
No — it can actually hurt performance by adding memory and comparison overhead. useCallback is only beneficial when passing functions to memoized child components (React.memo) or when the function is listed as a dependency in another hook like useEffect.
List each prop used in the computation as a dependency: const result = useMemo(() => expensiveCalc(propA, propB), [propA, propB]). The memoized value recomputes only when those specific props change, not on every render.