Middle+
What is useMemo? How does it differ from React.memo and useCallback?
sobes.tech AI
Answer from AI
useMemo — is a React hook that allows you to memoize a computed value so that it is not recalculated on every render if dependencies haven't changed. It is useful for performance optimization when computations are expensive.
React.memo — is a Higher Order Component (HOC) that memoizes the component itself, preventing re-rendering if props haven't changed.
useCallback is similar to useMemo, but it memoizes a function, returning the same function reference if dependencies haven't changed.
Example:
const expensiveValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
const memoizedCallback = useCallback(() => {
doSomething(a);
}, [a]);
const MemoizedComponent = React.memo(MyComponent);
Summary:
useMemo— memoizes a valueuseCallback— memoizes a functionReact.memo— memoizes a component based on props