# Fix React form state not updating on browser autofill

> How I fixed a React login form where browser autofill filled the fields but React state did not update, using a useRef and useEffect workaround to sync them.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2020-04-22 | Topics: [React](https://flaviocopes.com/tags/react/) | Canonical: https://flaviocopes.com/react-form-browser-autofill/

I stumbled upon an issue while working on a project I had a form built using [React](https://flaviocopes.com/react/), and how browser autofill interacted with it.

You know, when the browser puts your username/password automatically because you typed it already in the past?

That's autofill, and that's the cause of my problem. In particular I replicated it on Chrome and Firefox, but any browser might run into this.

The form was a usual and simple form built with the `useState` hook.

Here's an example `email` field of the form:

```js
import { useState } from 'react'

//...

const [email, setEmail] = useState('')
```

```jsx
<input
  id='email'
  type='email'                   
  name='email'
  value={email}
  onChange={(event) => setEmail(event.target.value)} 
/>
```

When you type the email in there, the `email` value is updated using `setEmail` and I'll have it available on the form submit event, so I can send it to the server.

At some point I realized the browser was autofilling the email and password, but React didn't recognize it!

Maybe because it fills the field before React is completely running, so it can't possibly intercept that event.

I researched a bit and got lost into a land of browser inconsistencies and differences in how autofill works, so I had to create a simple workaround.

I did it using `useRef` and `useEffect`:

```js
import { useState, useEffect, useRef } from 'react'
```

I create a ref:

```js
const emailField = useRef(null)
```

and in the JSX I attach it to the input field:

```jsx
<input
  ref={emailField}
  id='email'
  type='email'                   
  name='email'
  value={email}
  onChange={(event) => setEmail(event.target.value)} 
/>
```

Then I added a piece of code that every 100ms looks up the value of the field, and calls `setEmail()` to update it:

```js
useEffect(() => {
  let interval = setInterval(() => {
    if (emailField.current) {
      setEmail(emailField.current.value)
      //do the same for all autofilled fields
      clearInterval(interval)
    }
  }, 100)
})
```

It's not ideal, it involves DOM manipulation which is something we should avoid when using a library like React, but it works around this issue.

What if there's no autofill? This will simply wait until the first character is typed, and will stop the loop.
