The differences between React.memo, useCallback and useMemo
- Hank
- 03 Dec, 2024
In React, React.memo, useCallback and useMemo are three hooks that can help you optimize your React application. They are similar in some ways, but they are used for different purposes. In this article, I will explain the differences between them.
React.memo
React.memo is a higher-order component that can be used to prevent unnecessary re-renders of a functional component. It is similar to PureComponent in class components. When you wrap a functional component with React.memo, React will only re-render the component if the props have changed.
Here is an example:
import React from 'react';
const MyComponent = React.memo(({ name }) => {
return <div>{name}</div>;
});
In the example above, MyComponent will only re-render if the name prop has changed.
useCallback
useCallback is a hook that returns a memoized version of a callback function. It is useful when you need to pass a callback function to a child component, and you want to prevent the child component from re-rendering unnecessarily.
Here is an example:
import React, { useCallback } from 'react';
const MyComponent = ({ onClick }) => {
return <button onClick={onClick}>Click me</button>;
};
const ParentComponent = () => {
const handleClick = useCallback(() => {
console.log('Button clicked');
}, []);
return <MyComponent onClick={handleClick} />;
};
In the example above, MyComponent will only re-render if the onClick prop has changed.
useMemo
useMemo is a hook that returns a memoized value. It is useful when you need to calculate a value that is expensive to compute, and you want to prevent the value from being recalculated unnecessarily.
Here is an example:
import React, { useMemo } from 'react';
const MyComponent = ({ a, b }) => {
const result = useMemo(() => {
return a + b;
}, [a, b]);
return <div>{result}</div>;
};
In the example above, result will only be recalculated if the a or b props have changed.
Summary
React.memois used to prevent unnecessary re-renders of a functional component.useCallbackis used to return a memoized version of a callback function.useMemois used to return a memoized value.useCallbackis actually a special case ofuseMemo, where the memoized value is a function.