Skip to content

reset

Reset form state and values

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

Reset either the entire form state or part of the form state.

Rules

  • For controlled components like React-Select which do not expose a ref prop, you will have to reset the input value manually with setValue or connect your component via useController or Controller.

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

  • When you are subscribed to formState, it's important to decouple reset with handleSubmit. Both will update formState and handleSubmit is async by default. You can check out a working example below:

  • When invoking reset({ value }) without supplying defaultValues via useForm, the library will replace defaultValues with a shallow clone value object which you provide (not deepClone).

    // ❌ avoid the following with deep nested default values
    const defaultValues = { object: { deepNest: { file: new File() } } };
    useForm({ defaultValues });
    reset(defaultValues); // share the same reference
    
    // ✅ it's safer with the following, as we only doing shallow clone with defaultValues
    useForm({ deepNest: { file: new File() } });
    reset({ deepNest: { file: new File() } });
    
  • It's recommended to not invoke reset inside onReset or onSubmit callback.

    • We can't set value for native input during onReset event.

    • Because onSubmit callback is async and includes its validation when reset inside the callback it will intercept the result of formState update. This will be problematic when you subscribed to the formState.

Props

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

NameTypeDescription
valuesobject

An optional object to reset form values.

keepErrorsboolean

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

keepDirtyboolean

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

keepValuesboolean

Form input values will be unchanged.

keepDefaultValuesboolean

Keep the same defaultValues which are initialised via useForm.

keepIsSubmittedboolean

isSubmitted state will be unchanged.

keepTouchedboolean

isSubmitted state will be unchanged.

keepIsValidboolean

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

keepSubmitCountboolean

submitCount state will be unchanged.

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

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

  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) => {
    console.log(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
              defaultValue={`${item.firstName}`}
              {...register(`names[${index}].firstName`)}
            />

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

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