Controlled vs Uncontrolled Component in React.js

Saima Rahman
2 min readFeb 18, 2021

Using a simple counter form to go over this concept

React logo intro picture

I will assume before jumping into this topic that you have worked with React before and know at least some of it!

We have built applications with React, but often times we do not question why and how these things are happening.

Using React Hooks, I have built a simple React Counter App.

import React, { useState } from 'react';
import ReactDOM from 'react-dom';
const App = ()=>{const [count, setCount] = useState(0)let add = (evt) => {
setCount(count + 1)
}
let substract = () =>{
setCount(count - 1)
}
return(
<section>
<h2>Counter</h2>
<div>
<button id="add" onClick={add}>+</button>
<input
type = "text"
aria-label = "count"
value = {count}
/>
<button onClick={substract}>-</button>
</div>
</section>
)
}
ReactDOM.render(<App />, document.getElementById('root'));

If we look at the input field, it is now controlled; meaning React.js can control the input field and not the user. We can certainly make it uncontrolled if we change the attribute of “value” to “defaultValue” inside the input field. This will allow the user to type inside the input field, and so it will no longer be controlled by React and the numbers won’t increment or decrement.

We can make this input field controlled and make sure the users can type too, just by adding the onChange function inside the input field and changing the type attribute to number to avoid any error when the user types. Also, we want to make sure to use the parseInt() function, because input values always return strings. This will avoid appending a number to a string.

CheatSheet:

  • When you see an attribute called “defaultValue”, this would mean an uncontrolled component or not controlled by React.
  • When the user has the ability to change something without javascript (defaultValue) it is not controlled, you will see this on traditional HTML forms.
  • Controlled components allow us to manipulate more than one value.

--

--