React.memo
is 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 as PureComponent
but instead of classes React.memo
is used for functional components.React.memo
memoizes the rendered output then skips unnecessary rendering. This helps to prevent unnecessary re-rendering of components and computations needed for component rendering.As an example implementation lets create a component which will:
Let’s create and add a function/method on
GreetUser
component 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>;
};
GreetingCount
and Button
components will show the count and increment greet count on click respectively and do not have any heavy computations.// greetingCount.js
const GreetingCount = ({ count }) => (
return <div>You greeted me {count} times.</div>;
);
// button.js
const Button = ({ title, onClick }) => (
<button onClick={onClick}>{title}</button>
);
And the parent component will import all these components and have a method to update the greetings count.
//App.js
const App = () => {
const [greetCount, setGreetCount] = useState(0);
const onGreet = () => {
setGreetCount(greetCount + 1);
};
return (
<div className='App'>
<UserGreeting />
<GreetingCount count={greetCount} />
<Button title='Hi' onClick={onGreet} />
</div>
);};
As you can see that there is a delay for certain intervals before the UI updates after the button is clicked. This is because when we click on the button the state changes so every component is rerendered and the
GreetUser
component is rerendered as well. The getUserName
method is executed again due to a re-render of the GreetUser
component thus causing a delay in UI update.So the solution for the above problem is to use
React.memo()
. The React.memo()
method will memoize the component and does a shallow comparison of the component and since none of the props in GreetUser
React.memo()
and export it.const UserGreeting = () => {
// code here};
export default React.memo(UserGreeting);
As you can see now that the component does not re-render the
GreetUser
component and the UI is updated without any delay.You can find the complete example on
This post was first published on DevPostbyTruemark.