Skip to content

reset

Reset form state and values

reset: (values?: Record<string, any>, options?: Record<string, boolean>) => void

Reset the entire form state, fields reference, and subscriptions. There are optional arguments and will allow partial form state reset.

Props

Reset has the ability to retain formState. Here are the options you may use:

NameTypeDescription
valuesobject

An optional object to reset form values, and it's recommended to provide the entire defaultValues when supplied.

keepErrorsboolean

All errors will remain. This will not guarantee with further user actions.

keepDirtyboolean

DirtyFields form state will remain, and isDirty will temporarily remain as the current state until further user's action.

Important: this keep option doesn't reflect form input values but only dirty fields form state.

keepDirtyValuesboolean

DirtyFields and isDirty will remained, and only none dirty fields will be updated to the latest rest value. Check out the example.

Important: formState dirtyFields will need to be subscribed.

keepValuesboolean

Form input values will be unchanged.

keepDefaultValuesboolean

Keep the same defaultValues which are initialised via useForm.

  • isDirty will be checked again provided valued against the original defaultValues.

  • dirtyFields will be updated again provided valued limited to the root level against the original defaultValues.

keepIsSubmittedboolean

isSubmitted state will be unchanged.

keepTouchedboolean

isTouched state will be unchanged.

keepIsValidboolean

isValid will temporarily persist as the current state until additional user actions.

keepSubmitCountboolean

submitCount state will be unchanged.

Rules

  • For controlled components you will need to pass defaultValues to useForm in order to reset the Controller components' value.

  • When defaultValues is not supplied to reset API, then HTML native reset API will be invoked to restore the form.

  • Avoid calling reset before useForm's useEffect is invoked, this is because useForm's subscription needs to be ready before reset can send a signal to flush form state update.

  • It's recommended to reset inside useEffect after submission.

    useEffect(() => {
      reset({
        data: 'test'
      })
    }, [isSubmitSuccessful])
    

Examples

import React, { useCallback } from "react";
import { useForm } from "react-hook-form";

export default function App() {
  const { register, handleSubmit, reset } = useForm();
  const onSubmit = (data, e) => {};
  
  const resetAsyncForm = useCallback(async () => {
    const result = await fetch('./api/formValues.json'); // result: { firstName: 'test', lastName: 'test2' }
    reset(result); // asynchronously reset your form values
  }, [reset]);
  
  useEffect(() => {
    resetAsyncForm()
  }, [resetForm])

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("firstName", { required: true })} />
      <input {...register("lastName")} />
      <input type="reset" /> // standard reset button
      <input type="button" onClick={() => reset({ firstName: "bill" }); }} /> // reset form with values
      <input type="button" onClick={() => {
        reset({
          firstName: "bill"
        }, {
          keepErrors: true, 
          keepDirty: true,
          keepIsSubmitted: false,
          keepTouched: false,
          keepIsValid: false,
          keepSubmitCount: false,
        });
      }} />
    </form>
  );
}
import React from "react";
import { useForm } from "react-hook-form";

interface UseFormInputs {
  firstName: string
  lastName: string
}

export default function Form() {
  const { register, handleSubmit, reset, formState: { errors } } = useForm<UseFormInputs>();
  const onSubmit = (data: UseFormInputs) => {
    console.log(data)
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label>First name</label>
      <input {...register("firstName", { required: true })} />

      <label>Last name</label>
      <input {...register("lastName")} />

      <input type="submit" />
      <input
        type="reset"
        value="Standard Reset Field Values"
      />
      <input
        type="button"
        onClick={() => reset()}
        value="Custom Reset Field Values & Errors"
      />
    </form>
  );
}
import React from "react";
import { useForm, Controller } from "react-hook-form";
import { TextField } from "@material-ui/core";

export default function App() {
  const { register, handleSubmit, reset, setValue, control } = useForm();
  const onSubmit = data => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Controller
        render={({ field }) => <TextField {...field} />}
        name="firstName"
        control={control}
        rules={{ required: true }}
        defaultValue=""
      />
      <Controller
        render={({ field }) => <TextField {...field} />}
        name="lastName"
        control={control}
        defaultValue=""
      />

      <input type="submit" />
      <input type="button" onClick={reset} />
      <input
        type="button"
        onClick={() => {
          reset({
            firstName: "bill",
            lastName: "luo"
          });
        }}
      />
    </form>
  );
}
import React from "react";
import { useForm, Controller } from "react-hook-form";
import { TextField } from "@material-ui/core";

interface IFormInputs {
  firstName: string
  lastName: string
}

export default function App() {
  const { register, handleSubmit, reset, setValue, control } = useForm<IFormInputs>();
  const onSubmit = (data: IFormInputs) => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Controller
        render={({ field }) => <TextField {...field} />}
        name="firstName"
        control={control}
        rules={{ required: true }}
        defaultValue=""
      />
      <Controller
        render={({ field }) => <TextField {...field} />}
        name="lastName"
        control={control}
        defaultValue=""
      />

      <input type="submit" />
      <input type="button" onClick={reset} />
      <input
        type="button"
        onClick={() => {
          reset({
            firstName: "bill",
            lastName: "luo"
          });
        }}
      />
    </form>
  );
}
import React from "react";
import { useForm, useFieldArray, Controller } from "./src";

function App() {
  const {
    register,
    handleSubmit,
    reset,
    formState: { isSubmitSuccessful }
  } = useForm({ defaultValues: { something: "anything" } });

  const onSubmit = (data) => {
    // It's recommended to reset in useEffect as execution order matters
    // reset({ ...data })
  };

  React.useEffect(() => {
    if (formState.isSubmitSuccessful) {
      reset({ something: '' });
    }
  }, [formState, submittedData, reset]);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("something")} />
      <input type="submit" />
    </form>
  );
}
import React, { useEffect } from "react";
import { useForm, useFieldArray, Controller } from "react-hook-form";

function App() {
  const { register, control, handleSubmit, reset } = useForm({
    defaultValues: {
      loadState: "unloaded",
      names: [{ firstName: "Bill", lastName: "Luo" }]
    }
  });
  const { fields, remove } = useFieldArray({
    control,
    name: "names"
  });

  useEffect(() => {
    reset({
      names: [
        {
          firstName: "Bob",
          lastName: "Actually"
        },
        {
          firstName: "Jane",
          lastName: "Actually"
        }
      ]
    });
  }, [reset]);

  const onSubmit = (data) => console.log("data", data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <ul>
        {fields.map((item, index) => (
          <li key={item.id}>
            <input {...register(`names.${index}.firstName`)} />

            <Controller
              render={({ field }) => <input {...field} />}
              name={`names.${index}.lastName`}
              control={control}
            />
            <button type="button" onClick={() => remove(index)}>Delete</button>
          </li>
        ))}
      </ul>

      <input type="submit" />
    </form>
  );
}

Video

The following video explains in detail each different formState represents and functionality within the reset API.

Thank you for your support

If you find React Hook Form to be useful in your project, please consider to star and support it.

Edit