Junior — Middle
What principle distinguishes useMemo from useCallback in React?
sobes.tech AI
Answer from AI
The main difference between useMemo and useCallback in React is:
- useMemo memoizes the value returned by a function.
- useCallback memoizes the function itself, returning it.
That is, useMemo is used when you need to remember the result of a computation (for example, a complex calculation) so that it is not recalculated on every render, while useCallback is used when you need to keep a reference to a function to avoid recreating it, which is important when passing functions to child components or optimizing with React.memo.
Example:
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
const memoizedCallback = useCallback(() => doSomething(a), [a]);
Thus, useMemo returns a value, and useCallback returns a function.