DEV Community

Makoto Tsuga
Makoto Tsuga

Posted on

useFormState(useActionState)

I introduce "useFormState" which is new hook in React19. Now this hook is called "useActionState" as another name.
Note: The official React reference says that "useFormState" will change to "useActionState". It is expected that useFormState will no longer be available in the near future.

What is "useFormState"?

"useFormState" that allows the state to be updated based on the result of a function (form action). Please refer to this article for information about form actions.

Image description

How to use it.

  const [state, dispatch] = useFormState(putcart, null);
Enter fullscreen mode Exit fullscreen mode

useFormState can be used like useState.

  • The first element of the array is the state variable. The second element is a function for updating the state. At this time, the variable name needs to match the one specified in the Action attribute.

  • The first argument of useFormState is a function for performing updates. The second argument is the initial value of the state. In this case, null is passed as the initial value.

Example

The following example shows that by using useFormState, the state is being updated with a function called putcart.

FormComp.tsx

"use client";
import React from "react";
// import { useActionState } from "react";
import { useFormState } from "react-dom";
import { putcart } from "./functions";

const FormCop = () => {
  const [state, dispatch] = useFormState(putcart, null);
  return (
    <form
      className="bg-white w-1/3 text-center m-auto mt-20 p-5"
      action={dispatch}
    >
      <h1 className="font-bold">Shopping cart</h1>
      <input type="hidden" name="itemID" value={"1"} />
      <button className="bg-teal-400 w-3/4 p-2 text-white m-5" type="submit">
        ADD TO CART
      </button>
      {state && <p className="text-green-500">{state}</p>}
    </form>
  );
};

export default FormCop;
Enter fullscreen mode Exit fullscreen mode

functions.ts

"use server";
export const putcart = async (prev: string | null, formDate: FormData) => {
  await new Promise((resolve) => setTimeout(resolve, 1000));
  console.log("this comment is put debug console because in serverside");
  const itemID = formDate.get("itemID");
  if (itemID === "1") {
    return "you have added item to cart";
  }
  return prev;
};
Enter fullscreen mode Exit fullscreen mode

When the button is clicked, putcart is called by useFormState. At this time, the information from the form is passed as an argument to putcart. In this case, since the input value is 1, the string "you have added item to cart" is returned, and the state is updated with this value. Then, due to the condition state &&, the text "you have added item to cart" is displayed on the screen.

(Result)

Image description

Top comments (0)