Responding to Events
While updating a state, the proper way of calling the “setState” method is given as shown below.
Let us declare a state as
const [count, setCount] = useState(1);
And to update the state we do,
import { useState } from "react";
const User = ({ name, email }: { name: string; email: string }) => {
const [count, setCount] = useState(1);
const handleIncrementCounter = () => {
setCount(count + 1)
}
return (
<>
<div>
<p> Full Name: {name} </p>
<p> Email: {email} </p>
</div>
<div>
<h3>Current Level:{count}</h3>
<button onClick={handleIncrementCounter}>Increase level</button>
</div>
</>
);
};
export default User;
Can you tell the difference between
<button onClick={handleIncrementCounter}>Increase level</button>
<button onClick={() => handleIncrementCounter(incrementStep)}>Increase level</button>
<button onClick={handleIncrementCounter(incrementStep)}>Increase level</button>
The Answer
<button onClick={handleIncrementCounter}>Increase level</button>
-
This directly assigns the function handleIncrementCounter to the onClick event handler. When the button is clicked the function handleIncrementCounter will be called without any arguments.
<button onClick={() => handleIncrementCounter(incrementStep)}>Increase level</button>
-
This approach uses the arrow function to create an anonymous function that calls the handleIncrementCounter with the “incrementStep” argument when the button is clicked.
-
This is the correct way to pass arguments to Event Handlers.
<button onClick={handleIncrementCounter(incrementStep)}>Increase level</button>
-
This immediately invokes the handleIncrementCounter function with the “incrementStep” argument when the component renders. Not when the button is clicked but during component render.
-
INCORRECT WAY to use Event Handler as it will call the function right away, leading to unwanted execution of the function.
Click Here