Published on

TIL: synthetic change and blur events freeze React inputs

TIL: synthetic change and blur events freeze React inputs
Authors
On this page

A browser automation script kept freezing text inputs on a React app built with Material UI. The script set the value and dispatched change and blur:

input.value = 'hello'
input.dispatchEvent(new Event('change', { bubbles: true }))
input.dispatchEvent(new Event('blur', { bubbles: true }))

On plain HTML pages, that works fine. On React, the input froze. The text showed up for one frame, then vanished on submit, or the input stopped responding to keystrokes.

Two things broke

The value tracker. React replaces the input's value property with its own tracker. Assigning input.value directly goes through that tracker, which records the new value as already seen. When React processes the change event, it checks whether the value differs from what it tracked. It doesn't, so React skips onChange, and the next render puts the old state back.

The blur. MUI inputs listen to blur to commit validation and shrink floating labels. When the script fired blur right after change, the blur handler ran before React processed the state update. The component locked focus and threw away the uncommitted input.

The fix

Call the native setter and dispatch only input:

const prototype = window.HTMLInputElement.prototype
const nativeSet = Object.getOwnPropertyDescriptor(prototype, 'value').set

nativeSet.call(input, 'hello')
input.dispatchEvent(new Event('input', { bubbles: true }))

The native setter skips React's tracker, so React sees a real change. It listens for the bubbling input event at the app's root, updates its tracker, and fires its own synthetic onChange. If you need direct component access, you can also read the Fiber key memoizedProps.onChange from the DOM node.

The takeaway: when you automate React forms, don't dispatch synthetic change or blur events. Use the native prototype setter and dispatch a single bubbling input event.