Skip to content

setValue

필드 값 업데이트

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

이 함수는 등록된(registered) 필드의 값을 동적으로 설정하고, 유효성 검사 및 폼 상태 업데이트와 관련된 옵션을 제공합니다. 동시에 불필요한 리렌더링을 방지합니다.

Props

NameTypeDescription
namestring
  • 이름으로 단일 필드를 타겟.

  • 필드 배열과 함께 사용하는 경우.

    • 필드 배열에 replace update 와 같은 메서드를 사용할 수 있지만, 이 메서드들은 대상 필드 배열의 컴포넌트를 언마운트하고 다시 마운트하게 합니다.

      const { update } = useFieldArray({ name: 'array' });
      // 필드를 언마운트하고 업데이트된 값으로 다시 마운트
      update(0, { test: '1', test1: '2' })
      // 입력 값을 직접 업데이트
      setValue('array.0.test1', '1');
      setValue('array.0.test2', '2');
    • 존재하지 않는 필드를 대상으로 할 때는 새로운 필드를 생성하지 않습니다.

      const { replace } = useFieldArray({ name: 'test' })
      // ❌ 새로운 입력 필드를 생성하지 않음
      setValue('test.101.data')
      // ✅ 전체 필드 배열을 새로 고침
      replace([{data: 'test'}])
valueunknown

필드 값. 이 인자는 필수이며 undefined일 수 없습니다.

optionsshouldValidateboolean
  • 입력값의 유효성을 계산할지 여부. (구독 대상: errors).

  • 전체 폼의 유효성을 계산할지 여부. (구독 대상: isValid).

  • 이 옵션은 전체 폼의 터치된 필드가 아닌 특정 필드 레벨에서만 touchedFields를 업데이트.
setValue('name', 'value', { shouldValidate: true })
shouldDirtyboolean
  • 기본값과 비교해서 해당 입력이 수정되었는지 판단할지 여부를 결정합니다. (이 값은 dirtyFields에 구독됩니다.)

  • 기본값과 비교해서 전체 폼이 수정되었는지 판단할지 여부를 결정합니다. (이 값은isDirty에 구독됩니다.)

  • 이 옵션은 전체 폼 필드의 레벨이 아닌 특정 필드 레벨에서만 dirtyFields를 업데이트.
setValue('name', 'value', { shouldDirty: true })
shouldTouchboolean

입력 필드 자체를 터치된 상태로 설정할지 여부.

setValue('name', 'value', { shouldTouch: true })

Rules

  • 다음 조건에서만 리렌더링이 트리거됩니다:

    • 값 업데이트로 인해 에러가 발생하거나 수정된 경우.

    • setValue가 dirty나 touched와 같은 상태 업데이트를 유발하는 경우.

  • 두 번째 인자를 중첩된 객체로 만드는 것보다 필드 이름을 대상으로 설정하는 것이 좋습니다.

    setValue('yourDetails.firstName', 'value'); // ✅ 성능이 뛰어남
    setValue('yourDetails', { firstName: 'value' }); // 성능이 떨어짐
    register('nestedValue', { value: { test: 'data' } }); // 중첩된 입력값을 등록(register)
    setValue('nestedValue.test', 'updatedData'); // ❌ 관련 필드를 찾지 못함
    setValue('nestedValue', { test: 'updatedData' } ); // ✅ setValue가 입력을 찾고 업데이트
  • setValue를 호출하기 전에 입력의 이름을 등록하는 것이 좋습니다. 전체 필드 배열을 업데이트하려면 useFieldArray 훅이 먼저 실행되고 있는지 확인하세요.

    중요: 전체 필드 배열을 업데이트할 때는 setValue 대신 useFieldArrayreplace를 사용하세요. setValue를 사용한 전체 필드 배열 업데이트는 다음 메이저 버전에서 제거될 예정입니다.

    // 전체 필드 배열을 업데이트할 수 있습니다.
    setValue('fieldArray', [{ test: '1' }, { test: '2' }]); // ✅
    //등록하지 않은(unregistered) 입력 필드에 setValue를 사용할 수 있습니다.
    setValue('notRegisteredInput', 'value'); // ✅ 등록(registered) 권장
    // 다음 코드는 단일 입력 필드를 등록(register)합니다. (별도의 등록(register) 호출 없이)
    setValue('resultSingleNestedField', { test: '1', test2: '2' }); // 🤔
    // 등록된(registered) 입력 필드가 있는 경우, setValue는 두 개의 입력 필드를 모두 정확히 업데이트 합니다.
    register('notRegisteredInput.test', '1')
    register('notRegisteredInput.test2', '2')
    setValue('notRegisteredInput', { test: '1', test2: '2' }); // ✅ setValue를 두 번 호출하는 sugar syntax

Examples

CodeSandbox JS
import { useForm } from "react-hook-form";
const App = () => {
const { register, setValue } = useForm();
return (
<form>
<input {...register("firstName")} />
<button type="button" onClick={() => setValue("firstName", "Bill")}>
setValue
</button>
<button
type="button"
onClick={() =>
setValue("lastName", "firstName", {
shouldValidate: true,
shouldDirty: true
})
}
>
setValue options
</button>
</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

다음 동영상 튜토리얼에서는 setValue API에 대해 자세히 설명합니다.

지원해 주셔서 감사합니다

프로젝트에서 React Hook Form이 유용하다고 생각하신다면, 스타를 눌러 지원해 주시길 부탁드립니다.