Part 03 / Topic 3 of 7
Event handlers: passing a reference, not calling it
onClick and onChange both want a function - something for React to call later, when the click or keystroke actually happens. examples/02_event_handlers.jsx's GreetingForm wires up both kinds correctly:
// examples/02_event_handlers.jsx
export function GreetingForm() {
const [name, setName] = useState("");
const [greeting, setGreeting] = useState("");
function handleNameChange(event) {
setName(event.target.value);
}
function handleGreetClick() {
setGreeting(name.trim() ? `Namaste, ${name}!` : "Namaste, stranger!");
}
return (
<div className="greeting-form">
<label htmlFor="visitor-name">Your name</label>
<input id="visitor-name" value={name} onChange={handleNameChange} />
<button onClick={handleGreetClick}>Greet me</button>
{greeting && <p>{greeting}</p>}
</div>
);
}
onChange={handleNameChange} passes the function itself - no parentheses - so React holds onto it and calls it, with a real browser event, on every keystroke; event.target.value is the input's current text at that moment. onClick={handleGreetClick} does the same for clicks, with no event data this component needs. Typing "Priya" and clicking "Greet me" really shows "Namaste, Priya!"; clicking with the name left blank really shows "Namaste, stranger!" (both examples/02_event_handlers.test.jsx, driven by @testing-library/user-event, not a bare function call).
The one-character mistake that breaks this is adding parentheses - calling the handler instead of passing it. examples/02_event_handlers.jsx also exports BuggyGreetButton, kept here on purpose because the crash it produces is worth seeing for real, not just described:
// examples/02_event_handlers.jsx
export function BuggyGreetButton() {
const [greeting, setGreeting] = useState("");
return (
<div>
<button onClick={setGreeting("Namaste!")}>Greet me</button>
{greeting && <p>{greeting}</p>}
</div>
);
}
onClick={setGreeting("Namaste!")} calls setGreeting immediately, while React is still rendering this component, not later when the button is clicked - onClick ends up holding setGreeting's return value (undefined), not a function at all. Calling a setter during render schedules another render, which calls setGreeting(...) again during that render, and so on. Rendering BuggyGreetButton - with no click at all - really throws React's own guard rail against this (examples/02_event_handlers.test.jsx):
Too many re-renders. React limits the number of renders to prevent an infinite loop.
Done here? The practice set for Part 3 — including the solutions — is on the part page.