- Home
- /
- Tutorials
- /
- React Tutorial
- /
- Handling Events
Handling Events
Handling Events
You pass a function to an event prop. Calling it yourself - the missing arrow - is the most common React mistake there is.
Pass the function, do not call it
onClick={handleClick} hands React the function to run later. onClick={handleClick()} runs it immediately during render and gives React whatever it returned.
The missing arrow, shown
jsx
// Counts how many times the function has actually run.
let calls = 0
function greet() {
calls = calls + 1
return "a string, not a handler"
}
function Buttons() {
const [clicks, setClicks] = React.useState(0)
return (
<div>
{/* WRONG: greet() runs right now, during render. React receives
its return value — a string — which is not a handler at all. */}
<button onClick={greet()}>Wrong — already ran</button>{" "}
{/* RIGHT: React receives the function and calls it on click. */}
<button onClick={() => { greet(); setClicks((c) => c + 1) }}>
Right — runs on click
</button>
<p>greet() has run {calls} time(s). Clicks handled: {clicks}.</p>
<p style={{ color: "#64748b" }}>
Press the left button: nothing happens. Press the right one: the count moves.
</p>
</div>
)
}
const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(<Buttons />)