1

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>
    );
}
Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
user2952265
  • 1,590
  • 7
  • 21
  • 32

1 Answers1

2

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}
Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142