This topic is quite a simple to understand but dev always find hard to explain when interviewer ask
what is below warning? reason behind it?
While working with react often you found this warning while handling files and get back creating state to handle.
This relates to stateful DOM components (form elements) and the React docs explain the difference:
- A Controlled Component is one that takes its current value through props and notifies changes through callbacks like onChange. A parent component "controls" it by handling the callback and managing its own state and passing the new values as props to the controlled component. You could also call this a "dumb component".
- A Uncontrolled Component is one that stores its own state internally, and you query the DOM using a ref to find its current value when you need it. This is a bit more like traditional HTML. Most native React form components support both controlled and uncontrolled usage:
Example - Controlled Component:
const { useState } from 'react';
function Controlled () {
const [email, setEmail] = useState();
const handleInput = (e) => setEmail(e.target.value);
return <input type="text" value={email} onChange={handleInput} />;
}
Example - Uncontrolled component:
const { useRef } from 'react';
function Example () {
const inputRef = useRef(null);
return <input type="text" defaultValue="bar" ref={inputRef} />
}
What are the differences between Controlled and Uncontrolled Components in React JS?
- In a controlled component, form data is handled by a React component. Whereas in uncontrolled components, form data is handled by the DOM itself.
- Usage of Component State is a must for controlled components. Use of state is completely optional for uncontrolled components, but one must use Refs in it.
- With controlled components, we can validate as the input is being changed but the same is not possible with uncontrolled components.
Which one should we use?
It totally depends on your use case as mentioned before.
If you are using a large application where all the input components are already created as common components in order to maintain uniformity across apps, then it’s better to use them as controlled components as that will enable them to be used without passing the refs.
Similarly, if the component is being used in a relatively smaller project with direct HTML form elements implementation inside the render function and you don’t require the run time change events to do any actions, then it’s much easier to manage using uncontrolled components.
Conclusion
Controlled component is component that get the changed value from the callback function and uncontrolled component is component that have the one from the DOM. For example, When input value is changed,we can use onChange function in Controlled Component and also we can get the value using DOM like ref.
Hope you understand above do share and give feedback.
Top comments (0)