Skip to content

getFieldState

State of the field

getFieldState: object

This method is introduced in react-hook-form (v7.25.0) to return individual field state. It's useful in case you are trying to retrieve nested field state in a typesafe way.

Props

NameTypeDescription
namestring

registered field name.

formState

object

When set to true, field error will be retained.

Return

NameTypeDescription
isDirtyboolean

field is modified.

Condition: subscribe to dirtyFields.

isTouch

boolean

field has received a focus and blur event.

Condition: subscribe to touchedFields.

invalid

boolean

field is not valid.

Condition: subscribe to errors.

error

undefined | FieldError

field error object.

Condition: subscribe to errors.

Rules

  • name need to match registered field name.

    getFieldState('test');
    
    getFieldState('test'); // ✅ register input and return field state
    getFieldState('non-existent-name'); // ❌ will return state as false and error as undefined 
    
  • formState will need to subscribed.

    const { register, formState: { isDirty } } = useForm()
    register('test');
    getFieldState('test'); // ✅ register input and return field state
    
    ---------------------------
    
    // This is valid with useFormState as well
    const { isDirty } = useFormState();
    
    register('test');
    getFieldState('test'); // ✅ register input and return field state
    
    const { register } = useForm()
    register('test');
    getFieldState('test'); // ❌ formState is subscribed and no re-render to inform state update
    
    ---------------------------
    
    const { register, formState } = useForm()
    getFieldState('test', formState); // ✅ register input and return field state
    

Examples

import * as React from "react";
import { useForm } from "react-hook-form";

export default function App() {
  const {
    register,
    getFieldState,
    formState: { isDirty, dirtyFields, touchedFields, isValid }
  } = useForm({
    mode: "onChange",
    defaultValues: {
      firstName: ""
    }
  });

  // you can invoke before render or within the render function
  const fieldState = getFieldState("firstName");

  return (
    <form>
      <input {...register("firstName", { required: true })} />
      <p>{getFieldState("firstName").isDirty && "dirty"}</p>
      <p>{getFieldState("firstName").isTouched && "touched"}</p>
      <button type="submit" onClick={() => console.log(getFieldState("firstName"))}>
        field state
      </button>
    </form>
  );
}

Thank you for your support

If you find React Hook Form to be useful in your project, please consider to star and support it.

Edit