In this tutorial, you will learn the difference using controlled and uncontrolled components when creating a form using React.js. A normal web form will be made up from a number of components, like a textbox to get a user's emails, to a submit button, the form data and an action, e.g. you will need to handle the data somehow.
When you build a form using React.js you have two options. As the name implies, when you build a form in React.js using a controller component, React will manage the form data for you.
If you build a form using uncontrolled components, then it's up to you to write all the code to control the form.
Uncontrolled React Components
Uncontrolled Components behave like regular HTML forms. Uncontrolled Component, where we do not set the value of the input field, but we let the component manage its internal state.
When you write an uncontrolled component you will store in the forms state internally. If you want to access an uncontrolled component you query the DOM using 'ref'. You could then use state to control the value itself internally. So a basic example might look like this:
When Should You Use Uncontrolled Components?
When you build a form, I suggest you use controlled components to implement forms. I've built a few forms now within React and so far, I've never really needed to create a form using uncontrolled components.
Controlled components state is managed by the React framework. The easiest way to spot a controlled/non-controlled is the lack of the use of
ref. Most examples you will find online will be controlled. I'm a big fan of not reinventing the wheel unless needed. Unless you really need to manually query the DOM yourself to manage your form, I'd always recommend sticking with controlled components. An example of a controlled form can be seen below:
In the example above, we define a username and password in state. On each components
onChange handleInputUpdate which updates the state. React does everything else for you. In this architecture, when a user starts adding some text into the form, the state will be updated. This will cause React to re-run the render method and the UI will be updated accordingly. In this respect, React is managing the state and the rendering of the component for us. You do not need to manually get a reference and worry about re-rendering the UI yourself. Enjoy!