Junior — Middle
Can you explain the differences between React hooks useMemo and useCallback, and in which cases each of them should be used?
sobes.tech AI
Answer from AI
useMemo and useCallback are React hooks that help optimize performance by preventing unnecessary calculations and re-creation of functions.
-
useMemomemorizes the result of a function calculation and returns it, reusing the cached value if dependencies haven't changed. It is used for memoizing values (e.g., complex calculations). -
useCallbackmemorizes the function itself and returns it if dependencies haven't changed. It is used when passing functions down the component tree and it's important that the function reference remains stable (e.g., for optimizing child components that depend on function props).
Example:
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
const memoizedCallback = useCallback(() => { doSomething(a); }, [a]);
Use useMemo for memoizing values, and useCallback for memoizing functions.