sajad torkamani

The useActionState is a Client Component hook that helps you track the state of a server action. Here’s an example:

"use client";

import { useActionState } from "react";

async function createTodo(prevState, formData) {
  const title = formData.get("title");

  if (!title) {
    return { error: "Title is required" };
  }

  // ...store in DB
  return { success: true };
}

export default function TodoForm() {
  const [state, formAction, isPending] = useActionState(createTodo, {});

  return (
    <form action={formAction}>
      <input name="title" />
      <button type="submit" disabled={isPending}>
        {isPending ? "Saving..." : "Add Todo"}
      </button>
      {state?.error && <p style={{ color: "red" }}>{state.error}</p>}
      {state?.success && <p style={{ color: "green" }}>Todo added!</p>}
    </form>
  );
}

The useActionState(actionFn, initialState) function returns the following: