function Button() {
function handleClick() {
alert("Button clicked");
}
return <button onClick={handleClick}>Click</button>;
}Pass the function itself (handleClick), never call it (handleClick()). Calling it directly runs the function immediately during render, instead of waiting for the actual click.
function ProductList({ products }) {
function handleSelect(id) {
console.log("Selected:", id);
}
return (
<ul>
{products.map((p) => (
<li key={p.id} onClick={() => handleSelect(p.id)}>
{p.name}
</li>
))}
</ul>
);
}To pass a custom argument, wrap the call in an arrow function: onClick={() => handleSelect(p.id)}. This creates a brand-new function that calls handleSelect with the right value only when actually clicked.
function Form() {
function handleSubmit(event) {
event.preventDefault(); // stop the default full-page reload
console.log("Form submitted");
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
);
}React automatically passes an event object to your handler, giving access to details like event.target (covered fully with forms in Chapter 14) and event.preventDefault(), essential for stopping a form's default full-page-reload behavior on submit.
Writing onClick={handleClick()} instead of onClick={handleClick} calls the function immediately during rendering โ not when clicked โ and usually breaks the component entirely. This is one of the single most common React beginner mistakes.
Create a button that increments a click counter displayed on screen (you'll fully understand the state part next chapter โ for now, just log the click count to the console using a regular variable).
function ClickLogger() {
let clicks = 0;
function handleClick() {
clicks++;
console.log("Clicked", clicks, "times");
}
return <button onClick={handleClick}>Click Me</button>;
}
Q Why does my onClick handler run immediately when the page loads?
This happens when you accidentally call the function instead of passing it: onClick={doSomething()} runs immediately during render. Use onClick={doSomething} (no parentheses) or onClick={() => doSomething()} if you need to pass arguments.
Q Do I need preventDefault() on every form?
Only when you don't want the browser's default behavior โ most commonly, stopping a full page reload on form submission so you can handle the data with JavaScript instead, which is almost always what you want in a React app.