How to set the default value of a text input in React

Sometimes, it feels like I like to remind myself why I use React, and that the answer should always be “to make my life easier.” React should simplify my life.

One of the things React does very well, right out of the box, is controlling HTML inputs. It turns bratty inputs into controlled, behaved little children. 😔

Here is an example of a simple form made in React that only has one input (a text input).

In React, I prefer to use “controlled inputs.” In the example above, I used what’s known as an “uncontrolled input.” Using uncontrolled inputs makes our lives harder. Because doing hard stuff is no fun, it’s better to use a controller input, making use of the hook React.useState. The next example demonstrates a controlled input.

While they look the same, the controlled input has 2 key differences:

  1. The Input component is created to keep track of the firstName value.
  2. An onChange handler is created to update the value of firstName when the user types in the input.

So knowing all this, how can we provide a default value to the input. I want you to answer this question with a one-line change.

Here’s the answer:

Now, the form has the default value of “Ankurito”, but as soon as we change the value, the state updates to the new value.

I am a human being.