What is the difference between controlled and uncontrolled components?
Answer
1. Controlled Components:
- React manages the state of the form element.
- The value of the input is set via state, and changes are handled with an onChange handler.
const [value, setValue] = useState("");
return <input value={value} onChange={(e)=> setValue(e.target.value)} />;
2. Uncontrolled Components:
- The DOM directly manages the state of the form element.
- Access the value using a ref.
const inputRef = useRef(null);
return <input ref={inputRef} />;