Next.js Discord

Discord Forum

Incompatibilities integrating form actions with react-hook-form

Unanswered
Asian black bear posted this in #help-forum
Open in Discord
Asian black bearOP
In an attempt to introduce better client-side validation using react-hook-form I ran into various incompatibilities with the design of form actions and was curious to what extent others have been successful. Originally I started with the following code:
function Submit() {
  const { pending } = useFormStatus()
  return <Button type="submit" disabled={pending}>Submit</Button>
}

function Form() {
  const [state, formAction] = useFormState(actionFn, undefined)
  return (
    <form action={formAction}>
      {/* ... */}
      <Submit />
    </form>
  )
}

This made it fairly convenient to return errors and display them conditionally. In an attempt to integrate react-hook-form for client-side validation prior to submitting data I ran into a few inconveniences:

1. useFormState and in particular useFormStatus only work when using the action prop of the form. A conventional client-side and "non-magical" onSubmit={handleSubmit(...)} allows me to manually invoke the action referred to as actionFn as part of the handler passed to handleSubmit but all the new hooks become useless as they don't work.
2. When using formState.isSubmitting of react-hook-form in combination with a manually invoked action isn't enough to replace the use of useFormStatus since the flag toggles back instantly despite the action still running on the server. This is particularly noticeable when using the returned formAction which isn't asynchronous and causes react-hook-form to think the form was fully submitted.
3. Attempting to use useTransition and calling startTransition with either actionFn or formAction in the submit handler causes an even weirder issue where the pending flag ends up being true without ever toggling back despite the action finishing.
4. Finally, by default the validation of react-hook-form is only triggered when attempting to submit the form which is not triggered at all when attempting to use an action without the handleSubmit callback. In that case changing the validation mode to onChange by default is causing a terrible UX in most cases where errors pop up despite the form not being fully finished.

Much to my dismay it feels like I should just drop react-hook-form entirely and purely rely on server-side validation and errors being propagated to the client in order to keep things simple rather than fighting to integrate both APIs. What's your experience with this so far?

0 Replies