Controlled vs Uncontrolled Component in React.js

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';

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.

Coach @FlatironSchool

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store