Track 02 · Lesson 9 of 17Inside the browser
- 01Events and bubbling
- 02What fires when you click or type
- 03Keyboard, input and focus events
- 04Default actions and preventDefault()
- 05Event delegation
- 06Listener options and cleanup
- 07Custom events
- 08Debounce and throttle
- 09Events in React
- 10The event loop
- 11Don't block the main thread
- 12The rendering pipeline
- 13Core Web Vitals
- 14HTTP caching
- 15Responsive design
- 16SEO basics
- 17Service workers and offline
Events in React
Lesson 9 of 17· 6 min
React wraps native events in its own "synthetic" event objects with the same familiar API, and uses delegation under the hood. A few behaviors surprise people coming from plain JavaScript. Try them.
React, for real
This page is built with React
React’s onChange is the native input event
0
React onChange calls
0
native change events
React fires onChange on every keystroke, like native input, so controlled inputs stay in sync. The native change only fires when you leave the field.
The classic onClick mistake
- Render the component, then press Save.
function SaveButton({ id }) {
// Wrong: calls save during render, onClick gets its return value
// <button onClick={save(id)}>Save</button>
// Right: pass a function for React to call on click
return <button onClick={() => save(id)}>Save</button>;
}
function Search() {
const [q, setQ] = useState("");
// onChange runs on every keystroke, like the native input event
return <input value={q} onChange={(e) => setQ(e.target.value)} />;
}
function Form() {
const onSubmit = (e) => {
e.preventDefault(); // same as in plain JavaScript
console.log(e.nativeEvent); // the original browser event
};
return <form onSubmit={onSubmit}>…</form>;
}Where React differs#
onChangefires on every keystroke, like the nativeinputevent, not like nativechange. That's what keeps controlled inputs in sync.onFocusandonBlurbubble in React, because React builds them onfocusinandfocusout.- Listeners live at the root. Since React 17, React attaches one listener per event type to your app's root container and dispatches to your components itself: delegation, exactly as in the earlier lesson.
e.nativeEventgives you the original browser event when you need it, andonClickCapturelistens in the capture phase.
Pass the function, don't call it#
onClick={save()} calls save while React is rendering, and hands onClick whatever save returned, usually undefined. Pass the function itself, onClick={save}, or wrap it when you need arguments: onClick={() => save(id)}.
Check yourself