In this tutorial, you will learn the difference between using a controlled and an uncontrolled component when creating a form using ReactJS. A normal web form will be made up of a number of elements, a textbox to get a user's emails, a checkbox to confirm the T&Cs, a submit button, etc... When the user submits the form, the data will need to be processed somehow. This poses the question, how? When you build a form using ReactJS you have two options, controller and uncontrolled. When you build a controller component, React will manage the form data handling 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. Interested to know the differences, read on!
Uncontrolled React Components
Uncontrolled components are not managed by React. In an uncontrolled component, the component is responsible for managing its internal state, data is stored and accessed in the DOM directly. If you want to store data like this you use the
ref modifier. You could then use
ref to access data and manage a components state yourself internally. For example:
ref. If you encounter it you, be wary that data is being accessed in the DOM rather than the virtual DOM.
In a controlled component, the React framework manages the components state. Most examples you will find online will be controlled components. 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 form written using a controller approach can be seen below:
In the example above, two properties are bound to the components internal state, username and password. On each form element, an event handler is defined on the
onChange event. These handlers both call a function called
handleInputUpdate(). The purpose of this function is to update the components internal state. ReactJS 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. The React framework will also try and run optimisations into the background, so your form component runs as effectively as possible. This is why controller components are great! If you ever run into a job interview question that asks you how you would build a form in React you can now say how and why! Happy Coding 🤘