What would be the common mistake of function being called every time the component renders?

Technology CommunityCategory: ReactWhat would be the common mistake of function being called every time the component renders?
VietMX Staff asked 3 years ago

You need to make sure that function is not being called while passing the function as a parameter.

render() {
  // Wrong way: handleClick is called instead of passed as a reference!
  return <button onClick={this.handleClick()}>Click Me</button>
}

Instead, pass the function itself without parenthesis:

render() {
  // Correct way: handleClick is passed as a reference!
  return <button onClick={this.handleClick}>Click Me</button>
}