useActionState
useActionState is a hook in React that can be used to manage form state and actions in a more streamlined way. It handles the form submission and maintains the state, reducing the need for manual state management and action handling in forms.
Importing the Hook​
Import the useActionState hook from the React DOM library:
import { useActionState } from "react-dom";
Using useActionState​
The useActionState hook can be used inside your functional component to manage form state and actions. Here's a breakdown of how to use it:
Basic Usage​
const [state, formAction] = useActionState(submitData, initialState);
Hook Parameters​
submitData: The function that is called when the form is submitted. This function should take two parameters: the current state and aFormDataobject.initialState: The initial value of the state when the form is not submitted.
Hook Return Values​
state: The current state that is being rendered in the component. This state is equal to the initial state.formAction: The new action that you can pass to theactionprop of your form element. This executes the action that you passed with the current state and returns a new, updated state.
Example​
Here is an example of how to use the useActionState hook in a form component:
import { useActionState } from "react-dom";
import { submitActionWithCurrentState } from "../../actions";
const ActionStateComponent = () => {
const [state, formAction] = useActionState(submitActionWithCurrentState, {
users: [],
error: null,
});
return (
<form action={formAction}>
<div>
<input type="text" name="username" placeholder="Enter your name" />
<input type="number" name="age" placeholder="Enter age" />
<button type="submit">Submit</button>
</div>
</form>
);
};
Handling Form Submission​
The submitActionWithCurrentState method returns a new state consisting of the modified users list and gives an error if a user with the given name already exists. You can render the list of users and error (if any) like this:
<div className="error">{state?.error}</div>
{state?.users?.map((user) => (
<div key={user.username}>
Name: {user.username} Age: {user.age}
</div>
))}
Explanation​
- The form uses the
formActionreturned by theuseActionStatehook for itsactionprop. - The state is updated based on the form submission and is re-rendered with the new data or error message.
Benefits​
Using the useActionState hook simplifies the process of managing form state and actions. It reduces the need for manual state management and ensures that the form state is always up-to-date with the latest submission.

If you try to submit an existing user name you get an error:
