With learning react over the past three weeks, there was a lot of discussion about controlled forms vs. uncontrolled forms, and a big emphasis on why we should use controlled components instead. Let's first break down exactly what the difference is between the two..
Forms -
Traditionally forms store & maintain their own state, and it will get updated when you query the DOM and pull the current value. React takes a different approach by taking the current value through props, storing the values to state inside the component, and monitoring any changes through the onChange
callback. The main difference is that a controlled component is all handled completely by react. Take a look and this screenshot of what a controlled form looks like, the key indicators are having the input value set to the state, and having an onChange
attribute on the input as well.
notice we attached the onChange
callback to the input, and every time there is a change on the input it is triggering a helper function, which will be taking in that value and setting it to state, which is either declared inside the component or passed down from a parent component. We then take the value=
attribute and assign our state to it. So now every time a change happens, it updates state, which is then assigned back to the value of the form in almost this looping type of way. This is what truly makes a controlled form, everything is handled within react and not pulled from the DOM.
There is very little reason to ever choose an uncontrolled form compared to a controlled one, in most cases you will always want it to be controlled with React. It allows you to have more flexibility with managing state inside the components, you can also have several inputs for one piece of data, and also allows you to have dynamic inputs as well.
If you are interested in learning more about controlled forms take a look at the documentation from react.js.
Top comments (1)
Great work, new concept I only learned once I got into React. Great writeup.