Here is my Game of Life project
In this react project we have to make the cells clickable.
I am handling the things like this :
function Square(props) {
return (
<div (...) onClick={() => props.onClick()} >
</div>
);
}
class Game extends React.Component {
(...)
handleCellClick(c) { (...) }
render {
(...)
const cells = this.state.matrice.map((cell, index) => {
return (
<Square color={cell} ref={index} onClick={() => this.handleCellClick(index)} />
);
});
}
}
It’s working fine BUT looking at react documentation on handling event I am afraid I am in the situation they give a warning about :
The problem with this syntax is that a different callback is created each time the LoggingButton renders. In most cases, this is fine. However, if this callback is passed as a prop to lower components, those components might do an extra re-rendering. We generally recommend binding in the constructor to avoid this sort of performance problem.
Therefore I tried to modify my code as follow :
function Square(props) {
return (
<div (...) onClick={props.onClick} >
</div>
);
}
class Game extends React.Component {
constructor(props) {
super(props);
(...)
this.handleCellClick = this.handleCellClick.bind(this);
}
handleCellClick(c) { (...) }
render {
(...)
const cells = this.state.matrice.map((cell, index) => {
return (
<Square color={cell} ref={index} onClick={this.handleCellClick(index)} />
);
});
}
}
but this is absolutely not working.
Can you confirm that my first version is actually doing some extra re-rendering lowering the performance ?
If yes how can I correct it using binding ?