When or not use a controlled component?

A view about controlled and uncontrolled component with ReactJS library

P.S.: this article is originally published on medium at 22/07/2019

Sometimes after a long period working with specifics libraries as React and Redux we get used to do things in a certain way then someone asks us “Why do you do this in this way? I saw a beautiful library that implements in another way with another concept ”, and when this happen it’s time to go back to concepts.

In ReactJS projects usually we make forms using third libraries that abstracts the form and inputs that in general use controlled components. So …

What is a controlled component?

A controlled component is when the value of an input element is controlled by React, that basically means that when an input changes its values it’s updated into the state of component. In a controlled component React state will be the single source of truth of your form.

What is a uncontrolled component?

An uncontrolled component is when the value of an input element is not controlled by React, working like form elements works outside React, basically it means that data form is handled by the DOM itself. In an uncontrolled component the DOM will be the single source of truth of your form.

How to choose between them?

The react documentation recommends the use of controlled components, but in some cases you could use uncontrolled component. As everything in technology, this decision depends on the necessity of your project or application. Some articles in internet talked about how to choose and here I will try to compilate their considerations based on Gosha Arinich article¹:

Which libraries can I use to make a form in react?

There are lot of libraries that we can use to create a form in react. Some of libraries that I used were redux-form, react-json-schemaform, formik, unform:

*weekly downloads at 17/07/2019

Conclusion

The Andy Edwards’s article² from 2016 consider uncontrolled components as an anti-pattern, and his arguments are very strong for me.

In my opinion the decision between controlled or uncontrolled components always rely on the necessity of the application.

I prefer use third libraries that implement controlled component because the predictability likewise s an application is always alive and growing it’s better to be prepared for when the things getting bigger.

References

Last updated

Was this helpful?