Skip to content

setValue

Update input value

setValue: (name: string, value: unknown, config?: Object) => void

This function allows you to dynamically set the value of a registered field. At the same time, it tries to avoid unnecessary rerender.

Rules

  • Only the following conditions will trigger a re-render:

    • When an error is triggered by a value update

    • When an error is corrected by a value update

    • When setValue is invoked for the first time and formState.isDirty is set to true

  • You can also set the shouldValidate parameter to true in order to trigger a field validation.

    setValue('name', 'value', { shouldValidate: true })
  • You can also set the shouldDirty parameter to true in order to set field to dirty.

    setValue('name', 'value', { shouldDirty: true })
  • It's recommended to target the field's name rather than make the second argument a nested object.

    setValue('yourDetails.firstName', 'value'); // ✅ performant
    setValue('yourDetails', { firstName: 'value' }); // less performant 
    
    register('nestedValue', { value: { test: 'data' } }); // register a nested value input
    setValue('nestedValue.test', 'updatedData'); // ❌ failed to find the relevant field
    setValue('nestedValue', { test: 'updatedData' } ); // ✅ setValue find input and update
    
  • It's recommended to register the input's name before invoking setValue. However, the following usages are still permitted.

    To update the entire Field Array, make sure the useFieldArray hook is being executed first.

    Important: use replace from useFieldArray instead, update entire field array with setValue will be removed in the next major version.

    // you can update an entire Field Array, 
    // this will trigger an entire field array to be remount and refreshed with updated values.
    setValue('fieldArray', [{ test: '1' }, { test: '2' }]); // ✅
    
    // you can setValue to a unregistered input
    setValue('notRegisteredInput', 'value'); // ✅ prefer to be registered
    
    // the following will register a single input (without register) 
    // and update its value in case you expected to be two inputs
    setValue('notRegisteredInput', { test: '1', test2: '2' }); // 🤔
    
    // with registered inputs, the setValue will update both inputs correctly.
    register('notRegisteredInput.test', '1')
    register('notRegisteredInput.test2', '2')
    setValue('notRegisteredInput', { test: '1', test2: '2' }); // ✅
    

Props

NameTypeDescription
namestring
  • Target a single input by its name.

  • When used with field array.

    • It's recommend to use field array's methods such as replace/update instead of setValue.

    • It will not create new field when target a none existing field.

      const { replace } = useFieldArray({ name: 'test' })
      setValue('test.101.data')
      // ❌ doesn't create new input
      replace([{data: 'test'}]) 
      // ✅ work on refresh entire field array
      
valueunknown

The value for the field. Make sure you supply the entire array when you update useFieldArray and value can't be undefined.

configshouldValidateboolean
  • Whether to compute if your input is valid or not (subscribed to errors).

  • Whether to compute if your entire form is valid or not (subscribed to isValid).

shouldDirtyboolean
  • Whether to compute if your input is dirty or not against your defaultValues (subscribed to dirtyFields).

  • Whether to compute if your entire form is dirty or not against your defaultValues (subscribed to isDirty).

shouldTouchbooleanWhether to set the input itself to be touched.
CodeSandbox
import * as React from "react";
import { useForm } from "react-hook-form";

const App = () => {
  const { register, handleSubmit, setValue } = useForm();

  const onSubmit = data => {
    console.log(data)
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("firstName")} />
      <input {...register("lastName")} />
      <button onClick={() => setValue("firstName", "Bill")}>
        Set First Name Value
      </button>
      <button
        onClick={() =>
          setValue("lastName", "Luo", {
            shouldValidate: true,
            shouldDirty: true
          })
        }
      >
        Set Last Name
      </button>
      <input type="submit" />
    </form>
  );
};
import * as React from "react";
import { useForm } from "react-hook-form";

type FormInputs = {
  firstName: string
  lastName: string
}

const App = () => {
  const { register, handleSubmit, setValue } = useForm<FormInputs>();

  const onSubmit = (data: FormInputs) => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("firstName", { required: true })} />
      <input {...register("lastName", { required: true })} />
      <button onClick={() => setValue("firstName", "Bill")}>
        Set First Name Value
      </button>
      <button
        onClick={() =>
          setValue("lastName", "Luo", {
            shouldValidate: true,
            shouldDirty: true
          })
        }
      >
        Set Last Name
      </button>
      <input type="submit" />
    </form>
  );
};
import React from "react";
import { useForm } from "react-hook-form";

type FormValues = {
  string: string;
  number: number;
  object: {
    number: number;
    boolean: boolean;
  };
  array: {
    string: string;
    boolean: boolean;
  }[];
};

export default function App() {
  const { setValue } = useForm<FormValues>();
  
  setValue("string", "test");
  // function setValue<"string", string>(name: "string", value: string, shouldValidate?: boolean | undefined): void
  setValue("number", 1);
  // function setValue<"number", number>(name: "number", value: number, shouldValidate?: boolean | undefined): void
  setValue("number", "error");
  
  return <form />;
}
import * as React from "react";
import { useForm } from "react-hook-form";

type FormValues = {
  a: string;
  b: string;
  c: string;
};

export default function App() {
  const { watch, register, handleSubmit, setValue, formState } = useForm<
    FormValues
  >({
    defaultValues: {
      a: "",
      b: "",
      c: ""
    }
  });
  const onSubmit = (data: FormValues) => console.log(data);
  const [a, b] = watch(["a", "b"]);

  React.useEffect(() => {
    if (formState.touchedFields.a && formState.touchedFields.b && a && b) {
      setValue("c", `${a} ${b}`);
    }
  }, [setValue, a, b, formState]);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("a")} placeholder="a" />
      <input {...register("b")} placeholder="b" />
      <input {...register("c")} placeholder="c" />
      <input type="submit" />

      <button
        type="button"
        onClick={() => {
          setValue("a", "what", { shouldTouch: true });
          setValue("b", "ever", { shouldTouch: true });
        }}
      >
        trigger value
      </button>
    </form>
  );
}

Video

The following video tutorial demonstrates setValue API in detail.

We Need Your Support

If you find React Hook Form to be useful in your React project, please star to support the repo and contributors ❤

Edit