Skip to main content

useFormStatus

useFormStatus is a hook in React that provides information about the form's status while submitting the form. This hook is part of the React DOM and can be used to handle form submissions more effectively by managing the pending state and accessing form data.

Importing the Hook​

Import the useFormStatus hook from the React DOM library:

import { useFormStatus } from "react-dom";

Using useFormStatus​

The useFormStatus hook can be used inside your functional component to get information about the form's status. Here's a breakdown of how to use it:

Basic Usage​

function MyFormComponent() {
const { pending, data } = useFormStatus();

return (
// JSX code for your component
);
}

Hook Return Values​

  • pending: A boolean value that indicates whether the form is in a pending state.
  • data: An object of type FormData that contains the values of the form fields.

Example​

Here is an example of how to use the useFormStatus hook in a form component:

import { submitAction } from "../../actions";
import { useFormStatus } from "react-dom";

const Form = () => {
const { pending, data } = useFormStatus();

return (
<div>
<input type="text" name="username" placeholder="Enter your name" />
<button disabled={pending} type="submit">
Submit
</button>
{pending && <p>Submitting {data?.get("username")}...</p>}
</div>
);
};

const FormStatusWithHooks = () => {
return (
<form
action={async () => {
await submitAction();
}}
>
<Form />
</form>
);
};

Explanation​

  • Instead of using onSubmit, the form uses the action prop.
  • The data object is used to access the form fields and render them dynamically.

Notes​

  • This hook can only be used inside a component that has a <form> element as its parent.
  • It only returns status information of the parent form element and not the <form> element rendered in the same component.

Benefits​

Using the useFormStatus hook improves reusability and simplifies handling form states across different components. You can use any number of forms inside the parent <form> element and get the form state with useFormStatus, reducing the need to implement the same logic multiple times.

Rendering form data with pending state

  • You can use any number of forms inside the parent <form> element and get the form state with useFormStatus hook. So, you do not need to implement the same logic every time. This improves reusability in the code.