react hook form watch method

 

https://github.com/gopinav/React-Hook-Form-Tutorials/blob/main/rhf-demo/src/index.css

why watch will be used in react hook form

Why is watch used in React Hook Form?

In React Hook Form, the watch function is used to monitor changes in form fields in real time. It allows you to retrieve the current value of a field (or multiple fields) and react to changes without re-rendering the entire form.


🔹 Common Use Cases for watch

  1. Real-time Field Monitoring
    • Update UI dynamically as the user types.
  2. Conditional Rendering
    • Show or hide fields based on another field's value.
  3. Enable/Disable Submit Button
    • Only enable the button when a field is valid.
  4. Live Validation
    • Perform validation checks as the user types.

🔹 Basic Example: Watching a Single Input

jsx

import { useForm } from "react-hook-form"; export default function App() { const { register, watch } = useForm(); // Watching the 'email' input field const email = watch("email"); return ( <div> <input {...register("email")} placeholder="Enter your email" /> <p>Live Email: {email}</p> </div> ); }

📌 What Happens Here?

  • As the user types, the email value updates in real-time without triggering a re-render.

🔹 Example: Conditional Rendering with watch

jsx

const { register, watch } = useForm(); const showExtraField = watch("hasExtraField"); return ( <form> <label> <input type="checkbox" {...register("hasExtraField")} /> Show Extra Field </label> {showExtraField && ( <input {...register("extraField")} placeholder="Extra field" /> )} </form> );

📌 What Happens Here?

  • The extra input field appears only when the checkbox is checked.

🔹 Example: Enable Submit Button Only When Form is Filled

jsx

const { register, watch } = useForm(); const name = watch("name"); const email = watch("email"); return ( <form> <input {...register("name")} placeholder="Name" /> <input {...register("email")} placeholder="Email" /> <button type="submit" disabled={!name || !email}>Submit</button> </form> );

📌 What Happens Here?

  • The Submit button stays disabled until both fields are filled.

⚡ Key Takeaways

watch allows real-time tracking of field values.
✅ It does not cause re-renders, improving performance.
✅ Useful for conditional rendering, live validation, and UI updates.

Comments

Popular posts from this blog

interview questions js[ Anurag Singh ProCodrr]

reactnative_creation