Using React useState with form inputs

As of React 16.8, ReactJs added hooks. State hooks is a way to have functional components and state at the same time (prior to this you had to have a class declaration if you needed internal state management in your component).

I won’t go into details about hooks but if you are keen, i recommend reading this article by Tyler McGinnis which covers the topic very well.

What I’d like to point out is something I came across recently when implementing state on a form input using the useState hook. I’ll skip some markup but here is a sandbox implementation of this use case you can play around with ;)

I start by declaring the state using useState hook:

  import React, { useState } from 'react';
    ...
    const [ username, setUsername ] = useState();

Then the markup looks like this:

  <input name="username" value={username} onChange={e => setUsername(e.target.value)} />

input’s value is initialized with a value of undefined if the hook is defined without a value

In a nutshell, the value of the username input should be updated to whatever the input target value is by setUsername function. When you try to edit the input you will get a warning like this:

Warning

React warning about changing uncontrolled input of type undefined

The reason this happens is because the input’s value is initialized with a value of undefined if the hook is defined without a value i.e. const [var, setVar] = useState(). This can be easily resolved by initializing the username to an empty string instead like so:

  const [username, setUsername] = useState('')

After that change the warning will disappear and your input will work as expected. Hope this helps anyone facing issues implementing useState with controlled form inputs.