The useActionState
hook in React is a powerful tool for managing form state and handling form submissions. It allows you to wrap form actions and access the current form state, resulting in more responsive and controlled form interactions.
import { useActionState } from "react";
import { addToCart } from "./actions.js";
function AddToCartForm({ itemID, itemTitle }) {
const [message, formAction, isPending] = useActionState(addToCart, null);
return (
<form action={formAction}>
<h2>{itemTitle}</h2>
<input type="hidden" name="itemID" value={itemID} />
<button type="submit">Add to Cart</button>
{isPending ? "Loading..." : message}
</form>
);
}
export default function App() {
return (
<>
<AddToCartForm itemID="1"
itemTitle="JavaScript: The Definitive Guide" />
<AddToCartForm itemID="2"
itemTitle="JavaScript: The Good Parts" />
</>
);
}
In this example, useActionState
wraps the addToCart
function, tracking form state, the submission action, and whether the form is currently submitting. This pattern enables feedback to users after form submission and simplifies asynchronous form handling.
The useActionState
hook makes managing form submissions in React more intuitive by offering a declarative and reactive way to handle form state and asynchronous actions. It enhances user experience through smoother interactions and clearer state feedback.