Middle
What is the difference between useMemo and useCallback?
sobes.tech AI
Answer from AI
useMemo and useCallback are React hooks that help optimize performance but serve different purposes:
-
useMemo — memoizes a value, meaning it returns a cached result of a function calculation to avoid recalculating it on every render if dependencies haven't changed.
-
useCallback — memoizes the function itself, returning the same function reference between renders if dependencies haven't changed.
Example:
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
const memoizedCallback = useCallback(() => {
doSomething(a, b);
}, [a, b]);
Use useMemo if you need to cache the result of a calculation. Use useCallback if you need to pass a function down the component tree and want to prevent it from being recreated (to avoid unnecessary re-renders of child components).