Reputation: 1630
Is providing a setState-function as onClick-property directly a bad thing, cause the function will be defined with every render again? Should it be declared as function instead, e. g. this.open?
render() {
return (
<div>
<button
type="button"
onClick={() => this.setState({ isOpen: !this.state.isOpen })}
/>
</div>
);
}
Upvotes: 1
Views: 61
Reputation: 104379
Cause the function will be defined with every render again?
Yes, btw it doesn't matter whether you are using block body or concise body of arrow function, each time a new function will get created. You should try to avoid arrow function inside JSX.
If you bind the method in the constructor then it will get created only once, and for each re-rendering same reference will be used.
Block Body: () => {....}
Concise Body: () => expression
Should it be declared as function instead?
As mentioned in the Doc:
In most of the cases its fine, but we generally recommend binding in the constructor or using the class fields syntax, to avoid this sort of performance problem.
Write it like this:
handleClick(){
this.setState(prevState => ({ isOpen: !prevState.isOpen }))
}
onClick={this.handleClick}
Upvotes: 2