Middle+
What is the difference between useMemo and React.memo? Is it possible to prevent a component wrapped in React.memo from re-rendering even if props change?
sobes.tech AI
Answer from AI
useMemo is a React hook that memoizes the result of a function computation to avoid recalculating it on every render if dependencies haven't changed. It is used inside functional components to optimize performance.
React.memo is a Higher Order Component (HOC) that memoizes the component itself, preventing it from re-rendering if props haven't changed based on a shallow comparison.
Main difference:
useMemomemoizes a value inside a component.React.memomemoizes the component itself, controlling its re-rendering.
You can make a component wrapped in React.memo not re-render even when props change by passing a custom comparison function (areEqual) as the second argument, which returns true for any changes, for example:
const MyComponent = React.memo(
function Component(props) {
// ...
},
(prevProps, nextProps) => true // always consider props equal
);
However, this is not recommended, as the component will never update even if the data has actually changed.