Performance: Form validation patterns
MEDIUM IMPACT
Form validation patterns affect page responsiveness and user interaction speed by controlling when and how validation logic runs during user input and form submission.
import { useState, useEffect } from 'react'; export default function Form() { const [formData, setFormData] = useState({ email: '' }); const [error, setError] = useState(''); const [debouncedEmail, setDebouncedEmail] = useState(''); useEffect(() => { const handler = setTimeout(() => { setDebouncedEmail(formData.email); }, 300); return () => clearTimeout(handler); }, [formData.email]); useEffect(() => { if (debouncedEmail && !debouncedEmail.includes('@')) { setError('Email must include @'); } else { setError(''); } }, [debouncedEmail]); function handleChange(e) { setFormData({ email: e.target.value }); } return ( <form> <input type="email" value={formData.email} onChange={handleChange} aria-invalid={!!error} aria-describedby="email-error" /> {error && <div id="email-error" role="alert">{error}</div>} </form> ); }
export default function Form() {
const [formData, setFormData] = React.useState({ email: '' });
const [error, setError] = React.useState('');
function handleChange(e) {
setFormData({ email: e.target.value });
if (!e.target.value.includes('@')) {
setError('Email must include @');
} else {
setError('');
}
}
return (
<form>
<input type="email" value={formData.email} onChange={handleChange} aria-invalid={!!error} aria-describedby="email-error" />
{error && <div id="email-error" role="alert">{error}</div>}
</form>
);
}| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Validate on every keystroke | Many state updates and DOM changes | Triggers 1 reflow per keystroke | High paint cost due to frequent error message toggling | [X] Bad |
| Debounced validation on input | Fewer state updates | Single reflow after user stops typing | Lower paint cost with fewer error toggles | [OK] Good |
| Validate only on submit (server-side) | Minimal DOM changes until submit | Single reflow on error display | Paint cost delayed but blocks interaction | [!] OK |
| Client + server validation with instant client feedback | Moderate DOM changes with controlled updates | Few reflows, mostly on error state changes | Balanced paint cost with good UX | [OK] Good |