Course contentsShow
← React
Lesson 452 of 2,39613. Controlled ComponentsFree lesson

The onChange Handler

onChange fires on every keystroke, updating state and allowing the component to re-render with the new value.

The onChange Handler

You'll learn: How React uses the onChange handler to capture every keystroke and update controlled component state in real-time.


What onChange Does

In a controlled component, the input's value comes from state. But how does typing actually update that state? That's where onChange comes in.

The onChange handler fires every time the user types a character (or deletes one, or pastes text). React calls your function with an event object, and you extract the new value to update state.

The Pattern

function NameInput() {
  const [name, setName] = useState('');

  function handleChange(event) {
    setName(event.target.value);
  }

  return <input value={name} onChange={handleChange} />;
}

When you type "A", onChange fires → setName("A") → component re-renders → input shows "A".

Type "B" next → onChange fires again → setName("AB") → re-render → input shows "AB".

This happens on every keystroke.

Why Both Props Are Required

  • value={name} makes the input display what's in state
  • onChange={handleChange} lets typing actually update that state

Without onChange, you'd have a read-only input. Without value, you wouldn't have a controlled component.

The Event Object

event.target refers to the input element itself. event.target.value is the input's current text content—exactly what the user typed.

Key Takeaway: onChange is the bridge that lets user input flow into state, firing on every keystroke to keep the component synchronized with what's displayed.