React.memo
is a higher-order component (HOC) that is similar to the PureComponent
in that it will only re-render if the props have changed. It’s specifically designed to optimize the performance of functional components in React.
useMemo
is a hook that allows you to memoize values. It’s similar to React.memo
, but it’s used inside a functional component rather than being used to wrap the component. It’s useful for optimizing the performance of expensive calculations that don’t need to be re-computed on every render.
Here is an example of how you might use React.memo
:
import React from 'react'; const MyComponent = ({ data }) => { return ( <div>{data.value}</div> ); } export default React.memo(MyComponent);
Here is an example of how you might use useMemo
:
import React, { useMemo } from 'react'; const MyComponent = ({ data }) => { const memoizedValue = useMemo(() => expensiveCalculation(data), [data]); return ( <div>{memoizedValue}</div> ); } export default MyComponent;
In the example above, the expensiveCalculation
function will only be called if the data
prop has changed. The result of the calculation will be stored in a cache and returned on subsequent renders if the data
prop has not changed. This can help to optimize the performance of your component by avoiding unnecessary calculations.