ReactEasy

How to handle events in React?

Pass a function to a camelCase event prop such as onClick, onChange or onSubmit. React calls it with a synthetic event object that wraps the native event. Pass the function itself (onClick={save}), not its result (onClick={save()}), and use an arrow function when you need arguments.

Basics

  • Naming: onClick, onKeyDown, onMouseEnter, onFocus, onPointerDown.
  • Arguments: onClick={() => remove(item.id)}.
  • Prevent default: e.preventDefault() (for example on links or onSubmit).
  • Stop propagation: e.stopPropagation().
  • Capture phase: add Capture, as in onClickCapture.
  • Typing: React.MouseEvent<HTMLButtonElement>, React.ChangeEvent<HTMLInputElement>, React.FormEvent<HTMLFormElement>.

Custom event props

Your components can accept callbacks like onSelect or onClose; by convention name props onX and handlers handleX.

Under the hood

React attaches one listener per event type at the root container (since React 17) and dispatches to your handlers, which keeps memory use low and works with multiple React roots. Event pooling was removed in React 17, so you can use the event object asynchronously.

Things to watch

  • Handlers run after the event; state updates inside them are batched.
  • Event handlers are the right place for side effects caused by user actions, rather than effects.
  • onChange in React fires on every keystroke (like the native input event), not only on blur.
  • Non-React listeners on window or document go in useEffect with cleanup.
  • React 19.3 adds onFullscreenChange and onFullscreenError events.

Code example

tsx
1import { useState } from "react";
2
3export function EventsDemo() {
4 const [log, setLog] = useState<string[]>([]);
5 const add = (msg: string) => setLog((l) => [msg, ...l].slice(0, 5));
6
7 function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
8 e.preventDefault(); // stop the page reload
9 const data = new FormData(e.currentTarget);
10 add(`submitted ${data.get("q")}`);
11 }
12
13 function handleKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
14 if (e.key === "Escape") e.currentTarget.value = "";
15 }
16
17 return (
18 <div onClickCapture={() => add("capture: div")}>
19 <form onSubmit={handleSubmit}>
20 <input name="q" onKeyDown={handleKeyDown} onChange={(e) => add(`typed ${e.target.value}`)} />
21 <button type="submit">Search</button>
22 </form>
23 <button onClick={(e) => { e.stopPropagation(); add("button only"); }}>Click</button>
24 <ul>{log.map((l, i) => <li key={i}>{l}</li>)}</ul>
25 </div>
26 );
27}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app