Skip to content

reset

Reset form state and values

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

Reset the entire form state, you also have the ability to only reset specific parts of the 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 hook your component with useController or Controller.

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

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

  • When invoking reset({ value }) without supply defaultValues at useForm, hook form will replace defaultValues with shallow clone value object which you have supplied (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() } });
    

Props

Reset have the ability remain formState update, here are the options in detail:

NameTypeDescription
valuesobject

An optional object to reset from 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 is initialised at useForm.

keepIsSubmittedboolean

isSubmitted state will be unchanged.

keepTouchedboolean

isSubmitted state will be unchanged.

keepIsValidboolean

isValid will be temporarily remain as the current state until further user's action.

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) => {
    // e.target.reset(); // HTML standard reset() function will only reset inputs' value
  };
  
  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 [submittedData, setSubmittedData] = React.useState({});

  const onSubmit = (data) => {
    setSubmittedData(data);
  };

  React.useEffect(() => {
    if (isSubmitSuccessful) {
      reset({ ...submittedData });
    }
  }, [isSubmitSuccessful, 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