DEV Community

Hamzah Ahmad
Hamzah Ahmad

Posted on

Enhancing React Form Handling with useTransition

The useFormStatus hook in React can be used to retrieve the status of the most recent form submission. It provides information such as the pending property, indicating if the form is currently submitting. This can be used to, for example, display loaders or disable submit buttons during submission.

However, there are a few notable caveats with this hook:

  • Component Placement: The hook must be called from a component rendered within the form. This often necessitates creating a separate component to be rendered inside the form, which some might find cumbersome.

  • Action Dependency: The hook functions correctly only if the form uses the action attribute. This poses a challenge if you prefer using the form's onSubmit event handler, especially for implementing client-side validations prior to submission.

To circumvent these issues, I've found that the useTransition hook can be used as an alternative. The isPending property returned from the hook can be used to track the form action's pending state.

const { register, handleSubmit } = useForm({
    resolver: zodResolver(CreatePostSchema),
  });

  const [isPending, startTransition] = useTransition();
  const onSubmit = async (data) => {
    startTransition(async () => {
      const res = await createPost(data);
      if (res?.error) {
        toast.error(res?.error as string);
      }
    });
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("title")} placeholder="Title" />
      <button disabled={isPending}>Submit</button>
    </form>
  );
};
Enter fullscreen mode Exit fullscreen mode

Also, using the tried and tested technique of creating a loader state to keep track of the submission state of an action can also work, but it also has a slight caveat. This is explained well in Coding In Flow's short video here

Next.js is rapidly improving its API so the present issues might be fixed soon. useTransition provides a viable turnaround in the meantime.

Top comments (0)