The React team is updating a hook called useFormState
because it caused confusion and wasn’t just for forms. They’re making these changes:
- Renaming it to
useActionState
. - Adding a pending state to the returned values.
- Moving the hook from react-dom to the react package.
Now, other renderers like React Native can use it too. There are more benefits, like a “partial progressive enhancement” feature. But there are also new things to be careful about, which are documented in the PR.
This change aims to clear up confusion and enhance the functionality of the useFormState
hook.
Contents
useActionState Hook
The useFormState
hook, previously only available in the ReactDOM package, might confuse users into thinking it’s solely for managing form-related states. However, unlike useFormStatus
which deals with form statuses, useFormState
actually tracks the state of actions passed to it, regardless of whether they’re related to forms or not. Therefore, expecting useFormState
to provide a pending state for forms would be misleading.
To address this, the hook is renamed to useActionState
and now includes a pending state value. Additionally, it’s moved to the ‘react’ package to emphasize its broader usage beyond ReactDOM. This update allows users to track the state and pending status of any action, not just those related to forms.
How to use the useActionState
hook
import { useActionState } from "react"; function Form({ formAction }) { const [state, action, isPending] = useActionState(formAction); return ( <form action={action}> <input type="email" name="email" disabled={isPending} /> <button type="submit" disabled={isPending}> Submit </button> {state.errorMessage && <p>{state.errorMessage}</p>} </form> ); }
You can also use useActionState
outside of a element, providing flexibility in its usage:
0 Comments