Forms in React — React Technical Interview Questions & Answers
Forms in React
Forms in React
- A React form is usually controlled: the input value comes from state, onChange updates that state, onSubmit reads state and calls preventDefault so the browser does not reload. Email box: const [email, setEmail] = useState(''); <input value={email} onChange={e => setEmail(e.target.value)} />. Every keystroke goes through React. That is why you can disable Submit until email includes @.
- onSubmit={function go(e) { e.preventDefault(); console.log(email); }} — without preventDefault the page refreshes, React state dies, and it looks like ‘my form is broken’. That is a lab classic. type="submit" on the button, type="button" on extra actions inside the same form.
- Validation can live in state (error string under the field) or only on submit. Don’t mix uncontrolled defaultValue and value on the same input — React will warn. File inputs are a special case: often uncontrolled, you read e.target.files. Checkboxes and selects use the same controlled idea (checked / value + onChange).
- Let’s fill a login on the board. Type a@b.com → email state is a@b.com → Submit logs login a@b.com. Empty submit → setError('Email required') → red line under the box. One source of truth: React state, not the DOM.
- Libraries (Formik, React Hook Form) wait until this pattern is boring. In a fresher viva, write the controlled input yourself. Mention a library only if they ask how bigger apps scale validation.
- Trap: value={email} without onChange — the input freezes. Trap: onChange={setEmail} without e.target.value. Trap: storing the whole event in state. Trap: using a plain <a> or window.location inside submit instead of your API call.
- Forms in React — type asha@mail.com → state updates every key. Submit logs login asha@mail.com. preventDefault stops reload.
type → setEmail
│
▼
submit → preventDefault
│
▼
read stateTechnical Interview Tip: Controlled input + submit without reload.
Code Examples for Forms in React
Example
// Form
import { useState } from "react";
export default function Login() {
const [email, setEmail] = useState("");
function onSubmit(e) {
e.preventDefault();
console.log("login", email);
}
return (
<form onSubmit={onSubmit}>
<input value={email} onChange={(e) => setEmail(e.target.value)} />
<button type="submit">Go</button>
</form>
);
}
Forms in React — type asha@mail.com → state updates every key. Submit logs login asha@mail.com. preventDefault stops reload.
How to Explain Forms in React to an Interviewer
Why call preventDefault on submit?
Stop full page reload
What two props make an input controlled?
value onChange