React.memois a higher-order component provided by React that will return a memoized version of the component that only changes if one of the props has changed. It is the same asPureComponentbut instead of classesReact.memois used for functional components.

Why use React.memo?

React.memomemoizes the rendered output then skips unnecessary rendering. This helps to prevent unnecessary re-rendering of components and computations needed for component rendering.

React.memo in action

As an example implementation lets create a component which will:

  • Greet user
  • Show number of times user has greeted
  • Let user greet using button

Let’s create and add a function/method on

GreetUsercomponent that does the work of simulating some heavy computations while rendering the component.

// userGreeting.js

const UserGreeting = () => {
  const getUserName = () => {
    let i = 0;
    while (i < 3000000000) i++;

    return 'John Doe';
  };

  return <div>Hello {getUserName()},</div>;
};

#react #reactjs #javascript #coding #react-native

A Beginner's Guide to Performance Optimization Using React.memo
1.60 GEEK