← Back to Chapters

Reset & Clear Functions in React Forms

? Reset & Clear Functions in React Forms

⚡ Quick Overview

Resetting or clearing form fields is a very common task in React applications. After a successful form submission, when switching modes (edit vs. create), or when a user hits a Clear button, you often want to bring the form back to a clean or default state.

React gives you full control over this behaviour using:

  • ✅ Resetting controlled inputs by setting state back to initial values.
  • ✅ Clearing uncontrolled inputs by manipulating DOM nodes via useRef().
  • ✅ Resetting to default values instead of just empty strings.
  • ✅ Auto-resetting forms after submit using useEffect().

✨ Goal: Smooth, predictable, user-friendly form behaviour

? Key Concepts

  • Controlled components: Inputs whose values are stored in React state and updated via setState.
  • Uncontrolled components: Inputs that manage their own state in the DOM and are accessed via ref.
  • Initial / default values: A reusable object that represents the starting state of the form.
  • Reset vs. Clear: Reset = go back to known values; Clear = set everything to empty.
  • Auto reset: Use a flag plus useEffect() to reset after successful submission.

? Syntax & Theory

In React, you never directly modify the DOM for controlled inputs. Instead, you reset by changing state:

  • Define an initialForm or defaultValues object.
  • Pass this to useState() to initialise the form.
  • On reset, call setForm(initialForm) or setForm(defaultValues).

For uncontrolled components, React doesn't track the input value in state, so you can clear the DOM value directly using:

  • const inputRef = useRef();
  • inputRef.current.value = ""; to clear the input.

To auto-reset after submit, you can:

  • Use a submitted flag in state.
  • In useEffect(), watch this flag and reset the data when it becomes true.

? Code Examples

1️⃣ Resetting Controlled Components

All input values are stored in state. Resetting is as simple as setting the state back to the initial object.

? View Code Example
// Controlled form: reset fields by restoring initial state
import React, { useState } from "react";

function ResetControlledForm() {
const initialForm = { name: "", email: "", password: "" };
const [form, setForm] = useState(initialForm);

const handleChange = (e) => {
const { name, value } = e.target;
setForm({ ...form, [name]: value }); // Update only the changed field
};

const handleReset = () => {
setForm(initialForm); // Reset all fields back to initial empty values
};

const handleSubmit = (e) => {
e.preventDefault();
alert("Form submitted!"); // Simulate successful submit
handleReset(); // Clear fields after submit
};

return (
<form onSubmit={handleSubmit}>
<h4>Controlled Reset Example</h4>

<input
name="name"
className="form-control mb-2"
placeholder="Enter name"
value={form.name}
onChange={handleChange}
/>

<input
name="email"
className="form-control mb-2"
placeholder="Enter email"
value={form.email}
onChange={handleChange}
/>

<input
name="password"
type="password"
className="form-control mb-3"
placeholder="Enter password"
value={form.password}
onChange={handleChange}
/>

<button className="btn btn-success me-2">Submit</button>
<button
type="button"
className="btn btn-secondary"
onClick={handleReset}
>
Clear
</button>
</form>
);
}

export default ResetControlledForm; // Export component for use in your app

2️⃣ Clearing Uncontrolled Components with useRef()

Here, inputs are uncontrolled and their values are stored directly in the DOM. You clear them using refs.

? View Code Example
// Uncontrolled form: clear DOM values with refs
import React, { useRef } from "react";

function ClearUncontrolledForm() {
const nameRef = useRef();
const emailRef = useRef();

const clearFields = () => {
nameRef.current.value = ""; // Clear name input
emailRef.current.value = ""; // Clear email input
};

return (
<div>
<h4>Uncontrolled Clear Example</h4>
<input
type="text"
placeholder="Name"
ref={nameRef}
className="form-control mb-2"
/>
<input
type="email"
placeholder="Email"
ref={emailRef}
className="form-control mb-2"
/>
<button className="btn btn-warning" onClick={clearFields}>
Clear Inputs
</button>
</div>
);
}

export default ClearUncontrolledForm; // Use this when you do not need React state

3️⃣ Resetting to Default (Pre-filled) Values

Instead of clearing to empty strings, you can reset to meaningful default values like a default username or country.

? View Code Example
// Controlled form: reset to non-empty default values
import React from "react";

function ResetToDefault() {
const defaultValues = {
username: "Guest",
country: "India",
};
const [form, setForm] = React.useState(defaultValues); // Start with defaults

const handleChange = (e) => {
const { name, value } = e.target;
setForm({ ...form, [name]: value }); // Update specific field
};

const resetDefaults = () => {
setForm(defaultValues); // Restore original default settings
};

return (
<div>
<h4>Reset to Default Values</h4>
<input
type="text"
name="username"
className="form-control mb-2"
value={form.username}
onChange={handleChange}
/>
<select
name="country"
className="form-select mb-2"
value={form.country}
onChange={handleChange}
>
<option>India</option>
<option>USA</option>
<option>Japan</option>
</select>
<button className="btn btn-outline-primary" onClick={resetDefaults}>
Reset Defaults
</button>
</div>
);
}

export default ResetToDefault; // Handy for profile or settings forms

4️⃣ Auto Reset Using useEffect (After Submission)

You can automatically clear the form after a successful submission using a flag and useEffect().

? View Code Example
// Auto-reset form: useEffect runs after a successful submit
import React from "react";

function AutoResetForm() {
const [data, setData] = React.useState({ message: "" });
const [submitted, setSubmitted] = React.useState(false);

const handleSubmit = (e) => {
e.preventDefault();
alert("Form submitted!"); // Simulate API call or save
setSubmitted(true); // Trigger auto-reset
};

React.useEffect(() => {
if (submitted) {
setData({ message: "" }); // Reset the input value
setSubmitted(false); // Reset flag so it can trigger again later
}
}, [submitted]);

return (
<form onSubmit={handleSubmit}>
<h4>Auto Reset with useEffect</h4>
<input
type="text"
className="form-control mb-2"
placeholder="Type message"
value={data.message}
onChange={(e) => setData({ message: e.target.value })}
/>
<button className="btn btn-success">Send</button>
</form>
);
}

export default AutoResetForm; // Great for chat boxes or quick input forms

? Live Output / Behaviour Explanation

  • ResetControlledForm: Typing into the inputs updates React state. Clicking Clear or submitting the form resets all fields back to empty values using the shared initialForm object.
  • ClearUncontrolledForm: Inputs do not use React state. Instead, refs point to the DOM inputs, and clicking Clear Inputs sets their .value to an empty string.
  • ResetToDefault: Clicking Reset Defaults restores the username to "Guest" and the country to "India", even if the user changed them.
  • AutoResetForm: On submit, an alert is shown and the submitted flag is set. The useEffect() hook observes this flag, clears the message, and then switches the flag off again.

? Use Cases: When to Reset or Clear

  • ✅ After a successful submission or API response to prepare the form for new data.
  • ✅ When switching between form modes like Edit vs. New Entry.
  • ✅ To let users easily start over using a dedicated Clear button.
  • ✅ For restoring forms to known default values (profile, preferences, filters, etc.).

? Tips & Best Practices

  • Use setState() for controlled components; use ref.current.value = "" for uncontrolled inputs.
  • Provide a confirmation prompt before clearing large or complex forms.
  • Keep initial or default form data in a variable (not hard-coded multiple times) for easy reuse.
  • If using form libraries like Formik or React Hook Form, prefer their built-in reset methods for consistency and better validation handling.

? Try It Yourself / Practice Tasks

  1. Create a user registration form with Clear and Reset buttons.
  2. Reset the form automatically after a successful submission.
  3. Add one button that resets to default values and another that completely clears all inputs (empty strings).
  4. Experiment with both controlled and uncontrolled input resets in the same page.

Goal: Learn how to programmatically reset or clear React form fields using state, refs, and useEffect to build smooth and user-friendly form interactions.