Track 02 · Lesson 9 of 17Inside the browser

Track 02 · Inside the browser

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

  1. 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#

  • onChange fires on every keystroke, like the native input event, not like native change. That's what keeps controlled inputs in sync.
  • onFocus and onBlur bubble in React, because React builds them on focusin and focusout.
  • 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.nativeEvent gives you the original browser event when you need it, and onClickCapture listens 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

Why does onClick={save()} misbehave?