Skip to content
Event Handling
step 1/5

Reading — step 1 of 5

Read

~1 min readVirtual DOM & Diffing

Event Handling

User input: clicks, keypresses, form submissions. Components attach handlers.

python

Implementation:

  • During DOM creation, attach event listener for each onX prop.
  • During diff: if handler changed, replace listener.
  • During unmount: remove listeners.
python

React uses synthetic events:

  • Listeners attached at the root DOM (delegation).
  • Bubbling up triggers React's dispatcher.
  • React looks up handler in vtree, invokes.
  • Single listener per event type, scales to large apps.

Synthetic events also normalize cross-browser differences (IE vs Chrome event APIs).

Event handler closure trap:

javascript

If user clicks 3 times quickly, alert may show wrong count (closure captured at render). Use functional setState: setCount(c => c + 1).

Form handling:

  • Controlled: state owns value, onChange updates state.
  • Uncontrolled: ref to DOM input, read value on submit.
  • Controlled is React idiomatic.
python

Event bubbling:

  • Click on button → click event on button → bubbles to parent → up to body → window.
  • e.stopPropagation() to halt.
  • Preventing default: e.preventDefault() (e.g., form submit, link click).

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…