React: Controlled vs. Uncontrolled Forms

Brian Rhodes
JavaScript in Plain English
3 min readJul 19, 2021

--

At some point, you will come to terms that a lot of web design consists of forms. You can use forms for search bars, login, signup and the list goes on. Through learning React, you might have been told to write a single line of code in the input tag of your form that might have seemed redundant.

That line is:

(“term” being inside your state)

Let's start with a full component:

The entire idea of controlled components is to keep a single source of truth of where the data is stored and how to get it. If you know how event listeners and state work then you’ve most likely already been building most of what is considered a controlled component. When using React you want to keep things stored in React. Always avoid storing information in the HTML elements or more specifically the DOM. That is part of the purpose of using React’s state system. Not only does it handle user interactions, but it makes sure all information is stored within React. Otherwise, you would have to go into the DOM and manipulate things from there.

The most confusing part comes from the line that reads:

To start, the input tag already knows the value of the text you are typing. It is part of its job to store that information. However, as I said previously, we want to store all information in React, not the DOM. The purpose of value={this.state.term} is to default state to always be the value of the input. You are essentially overwriting the DOM information with the information in your state BUT both stored the same exact information you typed.

Why do this? Well “best practices” is one thing you can say. It’s probably something you’ve heard a lot with no explanation. You might think it’s just a pointless extra step but there is a reason…

This practice also allows you to do operations easier on your component. Since the final result always ends with the value equaling state, you can make changes to the data before it is pushed into the value. All you need are simple JavaScript methods. Whereas in an Uncontrolled component you would have to constantly reach out into the DOM and it could get a bit tricky.

Examples of this would be:

  1. Maybe you want to initialize this.state.term with words and not an empty string.
  2. Maybe you want the input field to always be upper case or lower case so you put the methods at the end of event.target.value .
  3. There are tons of things you can do. Give it a try!

More content at plainenglish.io

--

--

Software Developer | Writer at 𝘑𝘢𝘷𝘢𝘚𝘤𝘳𝘪𝘱𝘵 𝘐𝘯 𝘗𝘭𝘢𝘪𝘯 𝘌𝘯𝘨𝘭𝘪𝘴𝘩 | Written easy-to-understand explanations for myself and others.