Why do I need to pass an anonymous function into the onClick event?
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);
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>
}