Member-only story
Validating and managing user input represents some of the most crucial pieces of application logic. React includes great primitives for form handling, but orchestrating all the moving parts often results in verbose boilerplate code.
By leveraging dedicated hook-based form libraries, we can massively simplify managing key user workflows in React.
The Challenges of Form Logic
Let’s model a basic sign up flow:
function Form() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [emailError, setEmailError] = useState(null);
const validateEmail = email => {
// return true if invalid
};
const handleSubmit = e => {
e.preventDefault();
if (validateEmail(email)) {
setEmailError('Invalid email');
return;
}
alert('Successfully signed up!');
};
return (
<form onSubmit={handleSubmit}>
{/* Email input */ }
{emailError && <p>{emailError}</p>}
{/* Password input */}
<button>Submit</button>
</form>
);
}
This grows unwieldy even for simple flows:
- Verbose state/handlers all over