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.