Skip to content

How I fixed an issue with a React login form state and Browser autofill

New Course Coming Soon:

Get Really Good at Git

I stumbled upon an issue while working on a project I had a form built using 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:

import { useState } from 'react'

//...

const [email, setEmail] = useState('')
<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:

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

I create a ref:

const emailField = useRef(null)

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

<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:

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.

→ Get my React Beginner's Handbook
→ Read my full React Tutorial on The Valley of Code

Here is how can I help you: