Extracting Form Input Logic
What you'll learn: How to create a useInput custom hook that bundles the repetitive state and change handler needed for every controlled input.
The Problem: Boilerplate Everywhere
Every controlled form input requires the same two things: a value state and an onChange handler. When you have three inputs, you write this pattern three times. When you have ten inputs, you write it ten times. That's a lot of repetition.
The Solution: useInput Custom Hook
You can extract this pattern into a reusable custom hook:
function useInput(initialValue) {
const [value, setValue] = useState(initialValue);
const onChange = (e) => {
setValue(e.target.value);
};
return { value, onChange };
}
Now using it becomes elegant:
function LoginForm() {
const emailInput = useInput('');
const passwordInput = useInput('');
const handleSubmit = (e) => {
e.preventDefault();
console.log(emailInput.value, passwordInput.value);
};
return (
<form onSubmit={handleSubmit}>
<input type="email" {...emailInput} />
<input type="password" {...passwordInput} />
<button type="submit">Login</button>
</form>
);
}
Why This Works
The spread operator {...emailInput} expands to value={emailInput.value} onChange={emailInput.onChange}, which is exactly what your controlled input expects. You've turned six lines per input into one line.
Key Takeaway: The useInput custom hook encapsulates the value state and onChange handler pattern, eliminating boilerplate and making form logic reusable across your entire application.