Performance: Form handling in React
This affects the interaction responsiveness and rendering speed when users input data in forms.
function Form() { const inputRef = React.useRef(null); const handleSubmit = e => { e.preventDefault(); alert(inputRef.current.value); }; return <form onSubmit={handleSubmit}> <input ref={inputRef} /> <button type="submit">Submit</button> </form>; }
function Form() { const [value, setValue] = React.useState(''); return <input value={value} onChange={e => setValue(e.target.value)} />; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Controlled input with state on every keystroke | Many updates to virtual DOM and real DOM | Triggers 1 reflow per keystroke | High paint cost due to frequent updates | [X] Bad |
| Uncontrolled input with ref and submit handler | Minimal DOM updates | No reflows during typing | Low paint cost, only on submit | [OK] Good |
useState in React form handling?e.target.value in event handlers.setValue(e.target.value) updates state with the input's current value.function GreetingForm() {
const [name, setName] = React.useState('');
return (
<form>
<input value={name} onChange={e => setName(e.target.value)} />
<p>Hello, {name}!</p>
</form>
);
}function handleSubmit(e) {
alert('Submitted');
}e.preventDefault() inside the submit handler stops the reload.const [formData, setFormData] = React.useState({ email: '', password: '' });
function handleChange(e) {
// What goes here?
}Pass the test and this pattern moves unknown