React
Controlled vs Uncontrolled Components - Diepere uitleg
React of DOM bepaalt input state. De keuze matteert.
Controlled (React stuurt)
React state bepaalt input value React handles updates via onChange Full control in component Better untuk form validation, conditional inputs
Uncontrolled (DOM stuurt)
Input staat standalone, geen React state Use ref om value te lezen Lower overhead Goed voor file inputs, rare cases
Code Voorbeelden
JAVASCRIPTControlled vs Uncontrolled
// CONTROLLED
function ControlledForm() {
const [name, setName] = useState('');
return (
<input
value={name}
onChange={(e) => setName(e.target.value)}
/>
);
}
// UNCONTROLLED
function UncontrolledForm() {
const nameRef = useRef();
function handleSubmit() {
console.log(nameRef.current.value);
}
return (
<input ref={nameRef} />
);
}Relevante trefwoorden
controlleduncontrolledrefs