37. What is useActionState in React and when should it be used?
medium

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.

Key Concepts of useActionState

  • Form Action: A function responsible for handling form submissions and processing input values.
  • Form State: The dynamic state returned after a form submission, such as success messages or validation feedback.
  • useActionState Hook: A hook that provides access to the current form state, a new action to submit the form, and a pending flag to track form processing status.

Example: Adding Items to Cart with useActionState

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.


Conclusion

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.