React - Optimizing Performance With Higher Order Component React.memo
Hi everyone,
I was taking React.js course in TeamThreeHouse.I came across with React.PureComponent to optimize performance. I want to share an alternetive way to do with Higher Order Component React.Memo that comes with version React 16.6 which can be very useful in production to improve speed of our app.
Let's assume we have a parent component that render player component using map as follows:
{this.state.players.map((player, index) =>
<Player
score={player.score}
name={player.name}
id={player.id}
index={index}
key={player.id.toString()}
removePlayer={this.handleRemovePlayer}
changeScore={this.handleScoreEvent}
/>
)}
And this is the functional player component
const Player = (props) => {
console.log(props.name)
return (
<div className="player">
<span className="player-name">
<button className="remove-player" onClick={() => props.removePlayer(props.id)}>?</button>
{props.name}
</span>
<Counter score={props.score} index={props.index} changeScore={props.changeScore} />
</div>
);
}
You might, what's wrong with this?
Every time, we update score, it renders all components instead of one we manipulate.
We can fix it with React.PureComponent, but we need to refactor our code to Class component.
React.memo
To fix it, we can use React.memo:
React.memo is a higher order component . It’s similar to React.PureComponent but for function components instead of classes.
You can check official documentation for further info.
So what we did?
import React, { memo } from 'react'
And before export component, wrap it with higher order component memo.
export default memo(Player);
That's it!
Happy Coding