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:
state
: the last return value from your action (e.g., can be an object representing a success or error state).formAction
: The function you passed touseActionState
initially. Not sure what we’d use this for.isPending
: a boolean indicating if the action is currently running.