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>
    );
}
3
  • It's fine to use inline setState, though you may want to use the prevState syntax shown here Commented Jan 28, 2018 at 17:36
  • Nothing wrong with above code. Commented Jan 28, 2018 at 17:36
  • As long as you write Arrow function in render it will be called multiple times. Check this stackoverflow.com/questions/45053622/… Commented Jan 28, 2018 at 17:47

1 Answer 1

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}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.