Learning React via a tutorial and I don't understand why I have to create a new function to pass to a JSX onClick and can't just use the one returned from a React useState call.
The below works as it calls handleButtonClick on the button click, but it does not work if I just pass the setMessage function call with a string instead.
Works:
function App() {
const [message, setMessage] = React.useState('Javascript is so cool');
function handleButtonClick() {
setMessage('This is a new message');
}
return (
<div>
<h1>{message}</h1>
<button onClick={handleButtonClick}>Update The Message!</button>
</div>
);
}
Does Not Work:
function App() {
//Javascript goes here
const [message, setMessage] = React.useState('Javascript is so cool');
function handleButtonClick() {
setMessage('This is a new message');
}
return (
<div>
<h1>{message}</h1>
<button onClick={setMessage('Boom')}>Update The Message!</button>
</div>
);
I see that:
<button onClick={() => setMessage('Boom')}>Update The Message!</button>
works, but I don't get why it has to be setup like this and I can't just use the setMessage call in the same way I use the handleButtonClick call.
That's happened because when you put the function with parenthesis you call the function and if you only put the function without the parenthesis you pass the "pointer".
An example:
// log function
function logTheType(param) {
console.log(typeof param);
}
// sum function
function sum(a, b) {
return a + b;
}
// sum is a function
logTheType(sum);
// res: function
// you are calling sum and send the return to the logTheType
logTheType(sum(1, 5));
// res: number
// you pass an anonymous function
logTheType(() => sum(1, 5));
// res: function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With