How to Handle Form in Next.js: Simple and Correct Approach
useState to track input values and onSubmit event to process the form. Prevent the default form submission with event.preventDefault() to control behavior and update state as users type.Why This Happens
When handling forms in Next.js, a common mistake is not preventing the default form submission, which causes the page to reload and lose input data. Also, not using React state to track input values means the form cannot update or display user input properly.
import React from 'react'; export default function ContactForm() { return ( <form> <input type="text" name="name" /> <button type="submit">Submit</button> </form> ); }
The Fix
Use React's useState to store input values and add an onSubmit handler that calls event.preventDefault() to stop page reload. Update state on input changes to keep form data in sync.
import React, { useState } from 'react'; export default function ContactForm() { const [name, setName] = useState(''); function handleSubmit(event) { event.preventDefault(); alert(`Form submitted with name: ${name}`); } return ( <form onSubmit={handleSubmit}> <label htmlFor="name">Name:</label> <input id="name" type="text" value={name} onChange={(e) => setName(e.target.value)} required /> <button type="submit">Submit</button> </form> ); }
Prevention
Always use React state to control form inputs and prevent default form submission to avoid page reloads. Use controlled components by setting value and onChange. Validate inputs before submission and keep handlers simple.
Use linting tools like ESLint with React plugin to catch missing event.preventDefault() or uncontrolled inputs.
Related Errors
Uncontrolled to Controlled Input Warning: Happens when input switches from uncontrolled (no value) to controlled (with value). Fix by always setting value and onChange.
Form Submission Reloads Page: Fix by adding event.preventDefault() in submit handler.