useActionState - This feature is available in the latest Canary

Canary

The useActionState Hook is currently only available in React’s Canary and experimental channels. Learn more about release channels here. In addition, you need to use a framework that supports React Server Components to get the full benefit of useActionState.

Note

In earlier React Canary versions, this API was part of React DOM and called useFormState.

useActionState is a Hook that allows you to update state based on the result of a form action.

const [state, formAction, isPending] = useActionState(fn, initialState, permalink?);

Reference

useActionState(action, initialState, permalink?)

Call useActionState at the top level of your component to create component state that is updated when a form action is invoked. You pass useActionState an existing form action function as well as an initial state, and it returns a new action that you use in your form, along with the latest form state and whether the Action is still pending. The latest form state is also passed to the function that you provided.

import { useActionState } from "react";

async function increment(previousState, formData) {
return previousState + 1;
}

function StatefulForm({}) {
const [state, formAction] = useActionState(increment, 0);
return (
<form>
{state}
<button formAction={formAction}>Increment</button>
</form>
)
}

The form state is the value returned by the action when the form was last submitted. If the form has not yet been submitted, it is the initial state that you pass.

If used with a Server Action, useActionState allows the server’s response from submitting the form to be shown even before hydration has completed.

See more examples below.

Parameters

  • fn: The function to be called when the form is submitted or button pressed. When the function is called, it will receive the previous state of the form (initially the initialState that you pass, subsequently its previous return value) as its initial argument, followed by the arguments that a form action normally receives.
  • initialState: The value you want the state to be initially. It can be any serializable value. This argument is ignored after the action is first invoked.
  • optional permalink: A string containing the unique page URL that this form modifies. For use on pages with dynamic content (eg: feeds) in conjunction with progressive enhancement: if fn is a server action and the form is submitted before the JavaScript bundle loads, the browser will navigate to the specified permalink URL, rather than the current page’s URL. Ensure that the same form component is rendered on the destination page (including the same action fn and permalink) so that React knows how to pass the state through. Once the form has been hydrated, this parameter has no effect.

Returns