Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 40

Resetting Form State

Recommended resources

Hello! Welcome to the final lesson in our module on forms and event handling.

In the previous lesson, we built a robust submission process, complete with asynchronous API calls and clear loading and error states. We now have a form that provides excellent user feedback during the submission lifecycle. The last piece of the puzzle is to handle the "success" state gracefully. What should happen after the user's data is successfully sent?

This lesson will address our final learning outcome for this module: Reset form state after a successful submission. A clean, empty form invites the user to make another entry and prevents accidental resubmission of old data. We'll explore several techniques to achieve this, from the straightforward library-based approach to more fundamental React patterns that will deepen your understanding of how the framework manages state.

1. The Need for a Reset: Manual vs. Automated

After a successful submission, the form fields still contain the data that was just sent. This is not ideal. Manually clearing each input would be a poor user experience, and leaving the data there could lead to confusion. The solution is to programmatically reset the form's state back to its initial, empty condition.

React.js Reset to Initial State using Hooks Demonstration
This image illustrates the core concept: we have an initial state for our form (often empty strings or default values), and we need a mechanism to return to it on command.

If we were managing the form state with individual useState hooks, the process would be tedious and error-prone. You would need to call the setter function for every single piece of state.

React Hook Form (+ Zod) - Complete Tutorial

To see just how cumbersome this manual approach can be, watch this very brief clip from a ByteGrad tutorial.

Watch from 07:45 to 08:09. Notice the repetitive calls to setEmail, setPassword, etc. This is the boilerplate we want to avoid.

As you can see, this manual method doesn't scale well. For a form with ten fields, you'd need ten state-setting calls. Fortunately, the tools we're using provide a much more elegant solution.


2. The Idiomatic Way: Using reset() from React Hook Form

React Hook Form anticipates this exact need and provides a reset function as part of the useForm hook. This function, when called, will reset all registered field values to their defaultValues (or to be empty if no defaults are provided).

This is the most direct and idiomatic way to handle form resets when using this library.

React Hook Form (+ Zod) - Complete Tutorial

Now, let's watch the same video to see how React Hook Form solves the problem it just illustrated.

Watch from 15:36 to 15:50. Observe how a single call to the reset() function replaces all the manual setter calls.

Let's integrate this into the MyFinalForm component from our last lesson. We simply need to destructure reset from the useForm return object and call it within the try block after a successful submission.

import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
// ... other imports

function MyFinalForm() {
  const { 
    register, 
    handleSubmit, 
    setError,
    reset, // 1. Destructure the reset function
    formState: { errors, isSubmitting } 
  } = useForm<FormSchemaType>({
    resolver: zodResolver(FormSchema),
    defaultValues: { // It's good practice to define initial values
      email: '',
      // ... other fields initialized to empty
    }
  });

  const onSubmit = async (data: FormSchemaType) => {
    try {
      await submitWithFieldErrors(data);
      console.log('Success!');
      // 2. Call reset after the successful API call
      reset(); 
    } catch (error) {
      // ... error handling logic from previous lesson
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      {/* ... form fields and error messages ... */}
      <button type="submit" disabled={isSubmitting}>
        {isSubmitting ? 'Submitting...' : 'Submit'}
      </button>
      {/* ... */}
    </form>
  );
}

With one simple function call, our form now resets perfectly after each successful submission. This is the recommended approach for this specific use case.


3. A Fundamental React Pattern: Resetting State with a key

While reset() is perfect for our form, it's valuable to understand a more fundamental and powerful pattern for resetting a component's state in React. This technique leverages the key prop, which you've previously seen used for rendering lists.

The core principle is: React preserves a component's state as long as it's rendered in the same position in the UI tree. If you change a component's key, React will treat it as a completely new component instance, destroy the old one (and all its state), and mount a new one.

This is an incredibly powerful mechanism for a complete state reset.

Preserving and Resetting State

The official React documentation provides an excellent explanation of this concept. It shows how keys are not just for lists but are a general-purpose tool for establishing component identity.

Please read the sections titled "Option 2: Resetting state with a key" and "Resetting a form with a key". Focus on how changing the key on the <Chat> component forces it to be re-created from scratch, clearing the input field.

How could we apply this to our form? We could wrap our form in a parent component that manages a key in its state. After a successful submission, we update that key, forcing React to unmount the old form and mount a fresh one.

Consider this structure:

import { useState } from 'react';

// Assume FormComponent is our complete form with all its internal state
function FormComponent({ onSuccessfulSubmit }: { onSuccessfulSubmit: () => void }) {
  const { register, handleSubmit, formState: { isSubmitting } } = useForm();

  const onSubmit = async (data: any) => {
    // a successful API call
    await new Promise(resolve => setTimeout(resolve, 1000)); 
    onSuccessfulSubmit(); // Notify parent of success
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <p>This form will be completely re-mounted on reset.</p>
      <input {...register('name')} placeholder="Name" />
      <button type="submit" disabled={isSubmitting}>Submit</button>
    </form>
  );
}

// The parent component that controls the key
export default function FormContainer() {
  const [formKey, setFormKey] = useState(0);

  const handleSuccess = () => {
    // On success, we increment the key. This causes React to
    // destroy the old FormComponent and create a new one.
    setFormKey(prevKey => prevKey + 1);
  };

  return (
    <div>
      <h1>Submit Your Info</h1>
      <FormComponent key={formKey} onSuccessfulSubmit={handleSuccess} />
    </div>
  );
}

When to use this pattern:

  • Pro: It's a "sledgehammer" approach that guarantees a complete reset. If your form component has other internal states (e.g., useState for toggling UI elements) besides the form data, changing the key will reset everything.
  • Con: It can be less performant because it involves unmounting and remounting the entire component tree. For our current need—simply clearing form fields managed by React Hook Form—the reset() function is more precise and efficient. However, knowing this key pattern is essential for your advanced React toolkit.
Test your understanding!

You have a complex form component that not only uses useForm but also has several internal useState hooks for managing UI elements (e.g., toggling a preview panel, managing a step-by-step wizard). You want to reset everything to its initial state after a successful submission. Which method would be most effective and why: reset() from React Hook Form or changing the form's key?

Show answer

Changing the key would be the most effective method in this scenario.

The reset() function from React Hook Form will only reset the form field values it is managing. It will not affect the state held in separate useState hooks for the preview panel or the wizard steps.

By changing the key on the form component, you instruct React to discard the entire existing component instance and create a new one. This process naturally resets all state within that component, including React Hook Form's state and any other useState or useReducer hooks, providing the complete reset you need.


4. A Glimpse into Advanced State: Resetting with useReducer

As a final point and a preview of future topics, form state can also be managed with the useReducer hook, especially when state transitions are complex. This pattern, which you might recognize as being analogous to state management in Redux, also has a very clean way to handle resets.

A reducer function takes the current state and an action and returns the new state. A common action to implement is reset, which simply returns the predefined initialState.

How to use React useReducer hook like a pro

This article from devtrium provides a great introduction to useReducer, and it conveniently includes an example of a form with a reset action.

Read the section under the heading "Multiple pieces of state that rely on each other". Pay attention to the reducer function. Notice how the 'reset' case simply returns the initialValue object. Then see how the reset button calls dispatch({ type: 'reset' }).

The core logic looks like this:

const initialState = { value: '', touched: false };

function reducer(state: typeof initialState, action: { type: 'update' | 'reset', payload?: any }) {
  switch (action.type) {
    // ... other cases
    case 'reset':
      return initialState; // Simply return the initial state object
    default:
      throw new Error();
  }
}

function MyReducerForm() {
  const [state, dispatch] = useReducer(reducer, initialState);

  const handleSuccess = () => {
    dispatch({ type: 'reset' });
  };

  // ...
}

This pattern centralizes all state logic, including the reset logic, into a single function. We'll explore useReducer in much greater depth in our next module.



Conclusion

This lesson wraps up our comprehensive module on forms and event handling. You are now equipped to build forms that are not only interactive but also robust, user-friendly, and maintainable.

Key Takeaways:

  • Resetting a form after a successful submission is crucial for a good user experience.
  • The reset() function provided by React Hook Form is the most idiomatic and efficient way to clear form fields managed by the library.
  • Changing a component's key prop is a powerful, general-purpose React pattern that forces a complete re-mount, resetting all of its internal state. This is a vital tool for more complex reset scenarios.
  • State management patterns like useReducer also offer elegant solutions for state resets, which you will explore further.

Preview of the Next Module:

We have mastered managing state within a component and sharing it between a parent and child (lifting state up). But what happens when components that need to share state are far apart in the component tree? Passing props down through many layers, known as "prop drilling," can become cumbersome.

In our next module, "Advanced State, Context, and Refs," we will directly address this problem by introducing React's Context API, a powerful feature for providing data to all components below it in the tree without passing props manually at every level.