Skip to content

watch

입력 변경 사항 구독

</> watch: some overloads

이 메서드는 지정된 입력을 감시하고 해당 값을 반환합니다. 입력 값을 렌더링하고 조건에 따라 렌더링할 내용을 결정할 때 유용합니다.

Overloads

이 함수는 주로 두 가지 목적으로 사용됩니다:

  1. 필드의 값을 반환하며 동기화를 유지합니다.

    a. watch(name: string, defaultValue?): unknown

    b. watch(names: string[], defaultValue?): {[key:string]: unknown}

    c. watch(): {[key:string]: unknown}

  2. 주어진 콜백 함수로 구독을 시작합니다(구독 해제 함수 호출로 중지할 수 있음).

    a. watch(callback: (data, { name, type }) => void, defaultValues?): { unsubscribe: () => void }

이 네 가지 오버로드 각각에 대한 설명은 아래와 같습니다.

1-a. 단일 필드 감시하기 watch(name: string, defaultValue?: unknown): unknown


렌더링 외부에서 사용되는 단일 필드를 감시하고 구독합니다.

Params

NameTypeDescription
namestring감시할 필드의 이름
defaultValueunknown선택 사항. 필드의 기본 값

반환 단일 필드의 값을 반환합니다.

const name = watch("name")

1-b. 여러 필드 감시하기 watch(names: string[], defaultValue?: {[key:string]: unknown}): unknown[]


렌더링 바깥에서 사용되는 여러 필드를 감시하고 구독합니다.

Params

NameTypeDescription
namesstring[]감시할 필드의 이름들
defaultValue{[key:string]: unknown}선택 사항. 필드의 기본값

반환 필드 값의 배열을 반환합니다.

const [name, name1] = watch(["name", "name1"])

1-c. 전체 폼 감시하기 watch(): {[key:string]: unknown}


onChange 이벤트를 기반으로 전체 폼의 업데이트 및 변경 사항을 감시하고 구독하며, useForm에서 리렌더링을 수행합니다.

Params 없음

반환**** 전체 폼 값을 반환합니다.****

const formValues = watch()

2. 콜백 함수로 감시 시작하기 watch(callback: (data, { name, type }) => void, defaultValues?: {[key:string]: unknown}): { unsubscribe: () => void }


리렌더링을 트리거하지 않고 필드 업데이트/변경 사항을 구독합니다.

Params

NameTypeDescription
callback(data, { name, type }) => void모든 필드의 변경 사항을 구독하기 위한 콜백 함수
defaultValues{[key:string]: unknown}선택 사항. 폼 전체의 기본값

반환 unsubscribe 함수를 가진 객체.

useEffect(() => {
const { unsubscribe } = watch((value) => {
console.log(value)
})
return () => unsubscribe()
}, [watch])

Rules


  • defaultValue가 정의되지 않은 경우, watch의 첫 번째 렌더링은 register 이전에 호출되기 때문에 undefined를 반환합니다. 이 동작을 방지하려면 useForm에서 defaultValues를 제공하는 것이 좋지만 인라인 defaultValue를 두 번째 인수로 설정할 수 있습니다.
  • defaultValuedefaultValues를 모두 제공되면 defaultValue가 반환됩니다.
  • 이 API는 앱 또는 form의 루트에서 다시 렌더링을 트리거하므로 성능 문제가 발생하는 경우 콜백 또는 useWatch API를 사용하는 것이 좋습니다.
  • watch 결과는 값 업데이트를 감지하기 위해 useEffect의 deps 대신 렌더 단계에 최적화되어 있으므로, 값 비교를 위해 외부 커스텀 훅을 사용하는 것이 좋습니다.

Examples:


폼에서의 Watch

import React from "react"
import { useForm } from "react-hook-form"
interface IFormInputs {
name: string
showAge: boolean
age: number
}
function App() {
const {
register,
watch,
formState: { errors },
handleSubmit,
} = useForm<IFormInputs>()
const watchShowAge = watch("showAge", false) // 두 번째 인수로 기본 값을 제공할 수 있습니다.
const watchAllFields = watch() // 인수를 전달하지 않으면, 모든 것을 감시하게 됩니다.
const watchFields = watch(["showAge", "age"]) // 이름을 통해 특정 필드를 대상으로 할 수도 있습니다.
// watch의 콜백 버전입니다. 완료되면 unsubscribe하는 것은 사용자 책임입니다.
React.useEffect(() => {
const subscription = watch((value, { name, type }) =>
console.log(value, name, type)
)
return () => subscription.unsubscribe()
}, [watch])
const onSubmit = (data: IFormInputs) => console.log(data)
return (
<>
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("name", { required: true, maxLength: 50 })} />
<input type="checkbox" {...register("showAge")} />
{/*예(yes)를 선택하면 나이 입력란을 표시합니다*/}
{watchShowAge && (
<input type="number" {...register("age", { min: 50 })} />
)}
<input type="submit" />
</form>
</>
)
}
import React from "react"
import { useForm } from "react-hook-form"
function App() {
const {
register,
watch,
formState: { errors },
handleSubmit,
} = useForm()
const watchShowAge = watch("showAge", false) // 두 번째 인수로 기본 값을 제공할 수 있습니다.
const watchAllFields = watch() // 인수를 전달하지 않으면, 모든 것을 감시하게 됩니다.
const watchFields = watch(["showAge", "number"]) // 이름을 통해 특정 필드를 대상으로 할 수도 있습니다.
// watch의 콜백 버전입니다. 완료되면 unsubscribe하는 것은 사용자 책임입니다.
React.useEffect(() => {
const subscription = watch((value, { name, type }) =>
console.log(value, name, type)
)
return () => subscription.unsubscribe()
}, [watch])
const onSubmit = (data) => console.log(data)
return (
<>
<form onSubmit={handleSubmit(onSubmit)}>
<input type="checkbox" {...register("showAge")} />
{/* ‘예’ 선택에 따라 나이 input 필드를 표시 */}
{watchShowAge && (
<input type="number" {...register("age", { min: 50 })} />
)}
<input type="submit" />
</form>
</>
)
}

필드 배열에서의 Watch

import * as React from "react"
import { useForm, useFieldArray } from "react-hook-form"
type FormValues = {
test: {
firstName: string
lastName: string
}[]
}
function App() {
const { register, control, handleSubmit, watch } = useForm<FormValues>()
const { fields, remove, append } = useFieldArray({
name: "test",
control,
})
const onSubmit = (data: FormValues) => console.log(data)
console.log(watch("test"))
return (
<form onSubmit={handleSubmit(onSubmit)}>
{fields.map((field, index) => {
return (
<div key={field.id}>
<input
defaultValue={field.firstName}
{...register(`test.${index}.firstName`)}
/>
<input
defaultValue={field.lastName}
{...register(`test.${index}.lastName`)}
/>
<button type="button" onClick={() => remove(index)}>
Remove
</button>
</div>
)
})}
<button
type="button"
onClick={() =>
append({
firstName: "bill" + renderCount,
lastName: "luo" + renderCount,
})
}
>
Append
</button>
</form>
)
}
import * as React from "react"
import { useForm, useFieldArray } from "react-hook-form"
function App() {
const { register, control, handleSubmit, watch } = useForm()
const { fields, remove, append } = useFieldArray({
name: "test",
control,
})
const onSubmit = (data) => console.log(data)
console.log(watch("test"))
return (
<form onSubmit={handleSubmit(onSubmit)}>
{fields.map((field, index) => {
return (
<div key={field.id}>
<input
defaultValue={field.firstName}
{...register(`test.${index}.firstName`)}
/>
<input
defaultValue={field.lastName}
{...register(`test.${index}.lastName`)}
/>
<button type="button" onClick={() => remove(index)}>
Remove
</button>
</div>
)
})}
<button
type="button"
onClick={() =>
append({
firstName: "bill" + renderCount,
lastName: "luo" + renderCount,
})
}
>
Append
</button>
</form>
)
}

Video


지원해 주셔서 감사합니다

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