Share
what are controlled and uncontrolled components in react JS?
Question
In a controlled component, the form data is handled by the state within the
component, and in uncontrolled components where form data is handled by the DOM itself.
Controlled Component
- In a controlled component, the form data is handled by the state within the
component. The state within the component serves as “the single source of truth” for the
input elements that are rendered by the component. Controlled components have functions that govern the data passing into them on every onChange event occurs. This data is then saved to state and updated with setState() method. - It makes component have better control over the form elements and data.
- It does not maintain its internal state.
- Here, data is controlled by the parent component.
- It accepts its current value as a prop.
- It allows validation control.
Uncontrolled Component
- Uncontrolled components act more like traditional HTML form elements.
- The data for each input element is stored in the DOM, not in the component.
Instead of writing an event handler for all of your state updates, you use
a ref to retrieve values from the DOM. Refs provide a way to access DOM nodes or React elements created in the
render method. - It maintains its internal states.
- Here, data is controlled by the DOM itself.
- It uses a ref for their current values.
- It does not allow validation control.
- It has limited control over the form elements and data.
- Use controlled components whenever possible.
- Controlled components do not require a form element in order to be considered a controlled component.
- If a component has an input element that has a value attribute bound to state and an event handler to update said state, it is a controlled component.
- For pages that have a large number of input elements, it can be cumbersome (manageable) to work with controlled components.
- All state changes within a controlled component should be made via the setState function.
- Uncontrolled components store their data in the DOM like a traditional HTML input element.
Leave an answer