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
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>
}
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);
Because you need a function that gets called only in the instant that the button is clicked. If you pass alert('click')
then the parser will find a function call and execute it instantly when it is going over that file.