HomeTutorsContact

What is difference between React.memo and useMemo?

By Gulshan Saini
Published in ReactJS
January 01, 2023
1 min read

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.


Tags

#react
Previous Article
100 project ideas to learn ReactJS

Related Posts

ReactJS
What are HOC (higher order components)?
January 01, 2023
1 min
Gulshan Saini

Gulshan Saini

Fullstack Developer

Topics

JavaScript
Angular
ReactJS
Typescript
Linux

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.

Quick Links

Contact UsBrowserCSSPythonPuppeteer

Social Media