An uncontrolled component is a component that renders form elements,
where the form element's data is handled by the DOM (default DOM behavior).
To access the input's DOM node and extract its value you can use a ref.
Example - Uncontrolled component:
const { useRef } from 'react';
function Example () {
const inputRef = useRef(null);
return <input type="text" defaultValue="bar" ref={inputRef} />
}
In a controlled component, the form element's data is handled by the
React component (not DOM) and kept in the component's state.
A controlled component basically overrides the default behavior
of the HTML form elements.
We create a controlled component by connecting the form element
(<input>, <textarea> or <select>) to the state by setting its attribute
value and the event onChange.
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} />;
}