How to capture a value change made on the DOM in React

Alexandria Lalli
4 min readFeb 16


So you, like myself, have a weird scenario where you need to mutate the DOM directly in React. Why else would you have found this oddly specific blog post? It’s okay, I’ve got you. You’re in good hands now.

I won’t dive too deep into why this was required, but the top-level is… we are using a Google Tag Manager to set hidden fields in a controlled form.

This all seems fine and dandy, but when you manipulate the DOM on page load and then type into the input fields, the form’s state overwrites the newly-updated values.

tl;dr? The controlled form isn’t being told that the values changed. It looks a little something like this:

My problem is, we are using a third party to set the hidden field’s values by manipulating the DOM. I don’t know exactly how it works, but it functions by doing something along these lines:

To put it quite bluntly, if it were up to me, we wouldn’t be using this third party software, but part of being a Software Engineer is learning how to get around seemingly tricky coding problems like this!

So… how on earth do we tell React that we have made changes to an input’s value on the DOM?

I first tried to attach an event listener to each input. This didn’t work. I really can’t figure out why not, but my educated guess is because, again, React was not aware of the change being made so the onChange wasn’t firing.

My second attempt was to use a useRef hook to see if I could detect changes that way. While this does work usually, it does not work when you make direct changes to the DOM. I was getting closer to the final solution at this point, though.

I did want to mention that I toyed around with a million different solutions, one of which was the idea of putting these fields somewhere else on the page, outside of the controlled form, but I couldn’t come up with a clever solution as to how to pass the values. Plus, no matter what I did, updating the form’s state always made the hidden field’s…



Alexandria Lalli

Full-Stack Engineer, UX/UI Aficionado, and lover of coffee.

Recommended from Medium