Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need to pass an anonymous function into the onClick event?

I've been trying to learn the basics of React. However, I've come across a section in the tutorial that asks me to place an alert() inside of an onClick event as such:

        <button className="square" onClick={() => {alert("click");}}>
            {this.state.value}
        </button>

I don't understand why the arrow function is required - why can't I just have the alert() on its own?

The docs state:

Forgetting () => and writing onClick={alert('click')} is a common mistake, and would fire the alert every time the component re-renders.

Which is correct - I've tried this, and it does continually call alert(). But why? Isn't it supposed to fire onClick, and not on render? What does the anonymous function do that stops this behaviour?

like image 941
Weezeal Avatar asked Aug 07 '19 10:08

Weezeal


Video Answer


2 Answers

Because if you call a function, then the function runs. (And you get the return value from it)

const onClick = alert("hello");
console.log(onClick);

If you define a function (X) that calls a function (Y), then it doesn't call Y until you call X.

const onClick = () => alert("hello");
console.log(onClick);
like image 81
Quentin Avatar answered Oct 27 '22 13:10

Quentin


Basically there is differences between calling (Invoking) a function alert() and Defining (Expressing) a function () => {alert()}

When the code runs, i.e when react renders the component, any function call would run that function and that's why we can use IIFE (function() { } )() to inject functions to window object at runtime.

However, handling events with inline function call (like onclick={()=>{alert()}}) is not recommended because every time that event triggered, a new instance of that function would be created and it may slow down your app,

Instead you can DEFINE a function for handling events and just call it when that specific event triggered:

// Bad
render() {
  return <button onclick={() => {this.setState({btnClicked: true})}}> Click! </button>
}

// Good
render() {

  const handleClick = () => {
    this.setState({btnClicked: true})
  }

  return <button onclick={handleClick}> Click! </button>
}
like image 44
ABBAS mhs Avatar answered Oct 27 '22 13:10

ABBAS mhs