React components - Part II

Aktualisiert: 1. Nov 2018


Controlled vs uncontrolled components. What, why and when to use which one?


In the first part of the blog article I outlined the differences between the following component types:

  • Class vs. functional components

  • Stateful vs. Stateless components

  • Pure component vs. “Non Pure component”

In the second part we are going to look into controlled vs. uncontrolled components.


Controlled vs. uncontrolled components


When talking about controlled vs uncontrolled components, it’s usually in the context of html form elements.

Uncontrolled input components are just traditional html form inputs. They have their own internal state by default and update their state on user input. This behaviour is the same with React.

Let’s say you render a form with input fields in a form component like below. The state of the input field lives in the input field itself and not in the form component, which means the input field is not controlled from outside, but rather is uncontrolled.

To get the form values you use Reacts Ref.


Uncontrolled component - accessing value via Ref

On the other hand a controlled component gets its current value via prop and the value is changed via a callback. The state of the input fields lives in the form component or in any state store you might use.


Controlled component - accessing value own event handler

A controlled component is more powerful. You can give a user constant feedback about the users input. You could show an error message, disable the button or enforce some specific input format.


When to use which one?

I would favor controlled components, as they comply more to the overall React concept, but there is nothing bad in using the simpler uncontrolled form, if you don’t need any special validation behavior. Usually you would read that you shouldn’t overuse Refs, as the React documentation itself also points out. According to the docs, if you need to use Refs, this might indicate that the state should actually live at a higher level up the component hierarchy. But if this is not the case for you, you coudl still use Refs.




Nicole Hiller  |  Nana Janashia

Mail: info@nnsoftware.at

©2018 by nnSoftware