Step 1 of 5 · Reading · ~2 min
Read
Virtual DOM & Diffing
Event Handling
Handlers arrive as props whose names start with on. Creating a DOM node
attaches them; diffing a node swaps them.
The oldProps[k] !== v guard matters. Every render creates a fresh arrow
function, so without it you would detach and reattach every listener on
every render.
Synthetic events
React does not attach listeners to your elements at all. It attaches one native listener per event type at the root container. When an event bubbles up to it, React walks its own tree from the target upward and calls the handlers it finds along the way.
Two things fall out of that. Listener count stays flat no matter how many
nodes you render. And because React synthesises the propagation itself, it
can normalise the event object across browsers - stopPropagation still
stops the walk exactly where you would expect.
The event-dispatch exercise is this walk, with the tree given to you.
The stale closure
The interval was created during the first render, so its count is frozen
at 0 and it computes 1 forever. Nothing is broken - closures work
exactly as specified. The fix is to stop reading the captured value:
setCount(c => c + 1) asks the framework for the current one.
Controlled inputs
State drives value, and every keystroke round-trips through state, so the
component is the single source of truth - validate, format or reject on the
way through. The alternative, uncontrolled, leaves the value in the DOM
and reads it with a ref on submit: less code, but nothing to render from.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…