useWatch
</> useWatch: (UseWatchProps) => object
watch API와 비슷하게 동작하지만 커스텀 훅 수준에서 리렌더링을 격리하므로 애플리케이션 성능을 개선할 수 있습니다.
Props(속성)
| 이름 | 타입 | 설명 |
|---|---|---|
name | string | string[] | undefined | 필드 이름입니다. 반응형이므로 이 prop을 동적으로 변경하면 새 필드 이름을 구독합니다. |
control | Object | control 객체이며 useForm이 제공합니다. FormProvider를 사용한다면 선택 사항입니다. |
compute | function | v7.61.0부터 선택한 폼 값과 계산된 폼 값을 구독합니다.
|
defaultValue | unknown | 폼이 마운트되기 전이고 아직 현재 값이 없을 때 반환되는 대체 값입니다. 폼이 마운트되면 실제 현재 폼 값이 이 대체 값보다 우선합니다. |
disabled | boolean = false | v7.13.0부터 구독을 비활성화하는 옵션입니다. |
exact | boolean = false | v7.20.0부터 이름을 정확히 일치시킬지 지정합니다. false(기본값)이면 구독한 이름이 변경된 필드 이름의 접두사이거나 그 반대일 때 구독이 실행됩니다(예: "users"를 구독하면 "users.0.name" 업데이트를 받음). v7.81.0부터 true이면 구독한 "users.0.name" 필드 자체나 상위 경로 "users.0" 또는 "users"를 setValue로 설정할 때 업데이트를 받지만, 중첩된 하위 경로가 변경될 때는 실행되지 않습니다("users" 구독은 "users.0.name" 업데이트를 받지 않음). |
반환값
| 예시 | 반환값 |
|---|---|
useWatch({ name: 'inputName' }) | unknown |
useWatch({ name: ['inputName1'] }) | unknown[] |
useWatch() | {[key:string]: unknown} |
예시:
Form
import { useForm, useWatch } from "react-hook-form"
interface FormInputs {
firstName: string
lastName: string
}
function FirstNameWatched({ control }: { control: Control<FormInputs> }) {
const firstName = useWatch({
control,
name: "firstName", // without supply name will watch the entire form, or ['firstName', 'lastName'] to watch both
defaultValue: "default", // default value before the render
})
return <p>Watch: {firstName}</p> // only re-render at the custom hook level, when firstName changes
}
function App() {
const { register, control, handleSubmit } = useForm<FormInputs>()
const onSubmit = (data: FormInputs) => {
console.log(data)
}
return (
<form onSubmit={handleSubmit(onSubmit)}>
<label>First Name:</label>
<input {...register("firstName")} />
<input {...register("lastName")} />
<input type="submit" />
<FirstNameWatched control={control} />
</form>
)
}
import { useForm, useWatch } from "react-hook-form"
function Child({ control }) {
const firstName = useWatch({
control,
name: "firstName",
})
return <p>Watch: {firstName}</p>
}
function App() {
const { register, control } = useForm({
defaultValues: {
firstName: "test",
},
})
return (
<form>
<input {...register("firstName")} />
<Child control={control} />
</form>
)
}
고급 필드 배열
import { useWatch } from "react-hook-form"
function totalCal(results) {
let totalValue = 0
for (const key in results) {
for (const value in results[key]) {
if (typeof results[key][value] === "string") {
const output = parseInt(results[key][value], 10)
totalValue = totalValue + (Number.isNaN(output) ? 0 : output)
} else {
totalValue = totalValue + totalCal(results[key][value], totalValue)
}
}
}
return totalValue
}
export const Calc = ({ control, setValue }) => {
const results = useWatch({ control, name: "test" })
const output = totalCal(results)
// isolated re-render to calc the result with Field Array
console.log(results)
setValue("total", output)
return <p>{output}</p>
}