Description
I recently read an article on Medium about binding in react. Basically explaining how you should bind functions inside of the constructor of stateful components to prevent unnecessary rerenders in a component. It shows how using arrow function and .bind
causes function creation on the spot and makes it seem like new props are being received continuously even when it may not. This is bad and prevents optimizations according to the article. So great I know I should bind in constructor but what about binding methods with parameters not just calling them in stateful and stateless components?
Say theres something like the following:
// Using stateful components
class Something extends React.Component {
constructor () {
super()
this.doSomething = this.doSomething.bind(this)
}
doSomething (take, take2) {
return take + take2;
}
render () {
return (
<div>
<button onClick={this.doSomething(5, 6)}>clickMe!</button>
</div>
);
}
}
// Using stateless components
function Something (props) {
function doSomething (take, take2) {
return take + take2;
}
return (
<div>
<button onClick={doSomething(5, 6)}>clickMe!</button>
</div>
);
}
It throws an error because the call evaluates immediately to a number when it should be a function. This makes sense and the only way around this I've been able to go around this is using an arrow function in the onClick
() => doSomething(5, 6)
and that will run. But this will cause unnecessary rerenders that the article explained. So how could you do this better and prevent unnecessary rerenders in stateless and stateful components?