Skip to content

useController

React hooks for controlled component

useController:
(props?: UseControllerProps) => { field: object, fieldState: object, formState: object }

This custom hook is what powers Controller, and shares the same props and methods as Controller. It's useful to create reusable Controlled input, while Controller is the flexible option to drop into your page or form.

Props

The following table contains information about all the arguments for useController.

NameTypeRequiredDescription
namestringUnique name of your input.
controlObjectcontrol object is from invoking useForm. Optional when using FormProvider.
defaultValueanyThe same as an uncontrolled component's defaultValue. When passing a boolean value, it will be treated as checkbox input. For more details, see useForm's defaultValues section.
  • You need to either set defaultValue at the field-level or call useForm with defaultValues.

  • If your form will invoke reset with default values, you will need to call useForm with defaultValues instead of setting the defaultValue on individual fields.

rulesObjectValidation rules in the same format as for register.
rules={{ required: true }}

Return

The following table contains information about properties which useController produce.

React.RefObject
Object NameNameTypeDescription
fieldonChange(value: any) => void

A function which send value to hook form and should be assigned with onChange prop.

onBlur(value: any) => void

A function which send value to hook form and should be assigned with onBlur prop.

valueunknown

The value of this controlled component.

ref

Assign ref to component's input ref, so hook form can focus on the error input.

fieldStateinvalidboolean

Invalid state for current input.

isTouchedboolean

Touched state for current controlled input.

isDirtyboolean

Dirty state for current controlled input.

errorobject

error for this specific input.

formStateisSubmitSuccessfulboolean

Indicate the form was successfully submitted.

isDirtyboolean

Set to true after the user modifies any of the inputs.

isSubmittedboolean

Set to true after the form is submitted. Will remain true until the reset method is invoked.

dirtyFieldsobject

An object with the user-modified fields. Make sure to provide all inputs' defaultValues at the useForm, so hook form can compare with the defaultValue.

touchedFieldsobject

An object containing all the inputs the user has interacted with.

isSubmittingboolean

true if the form is currently being submitted. false if otherwise.

submitCountnumber

Number of times the form was submitted.

isValidboolean

Set to true if the form doesn't have any errors.

isValidatingboolean

Set to true during validation.

import React from "react";
import { TextField } from "@material-ui/core";
import { useController, useForm } from "react-hook-form";

function Input({ control, name }) {
  const {
    field: { ref, ...inputProps },
    fieldState: { invalid, isTouched, isDirty },
    formState: { touchedFields, dirtyFields }
  } = useController({
    name,
    control,
    rules: { required: true },
    defaultValue: "",
  });

  return <TextField {...inputProps} inputRef={ref} />;
}

function App() {
  const { control } = useForm();
  
  return <Input name="firstName" control={control} />;
}
import * as React from "react";
import { useForm, useController } from "./src";

function Input(props) {
  const { field, fieldState } = useController(props);

  return (
    <div>
      <input {...field} placeholder={props.name} />
      <p>{fieldState.isTouched && "Touched"}</p>
      <p>{fieldState.isDirty && "Dirty"}</p>
      <p>{fieldState.invalid ? "invalid" : "valid"}</p>
    </div>
  );
}

export default function App() {
  const { handleSubmit, control } = useForm({
    defaultValues: {
      FirstName: ""
    },
    mode: "onChange"
  });
  const onSubmit = (data) => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Input control={control} name="FirstName" rules={{ required: true }} />
      <input type="submit" />
    </form>
  );
}

Tips

  • Do not register input again. This custom hook is made to take care the registration process.

    const { field } = useController({ name: 'test' })
    
    <input {...field} /> // ✅ 
    <input {...field} {...register('test')} /> // ❌ double up the registration        
    
  • It's ideal to use single useController per component. If you need to use more than one, make sure you rename the prop or even consider to use Controller instead.

    const { field: input } = useController({ name: 'test' })
    const { field: checkbox } = useController({ name: 'test1' })
    
    <input {...input} />
    <input {...checkbox} />        
    
Edit