sajad torkamani

In a nutshell

useFormState is a hook that lets you create component state that’s updated when a form action is invoked.

The signature is:

const [formState, formAction] = useFormState(fn, initialState, permalink?);

You pass it a form action function (fn) as well as an initial state (initialState), and it returns a new action (formAction) that you can use in your form, along with the latest form state (formState). The latest form state is also passed to the function you provide (fn).

Here’s a simple example:

import { useFormState } from "react-dom"

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

function StatefulForm({}) {
  const [state, formAction] = useFormState(increment, 0)

  return (
    <form>
      {state}
      <button formAction={formAction}>Increment</button>
    </form>
  )

Parameters

  • actionFn: The function to be called when the form is submitted. This function will receive the previous state of the form (initially the initialState that you pass and then subsequently the previous returned value) as its initial argument, followed by the arguments that the form action normally receives.
  • initialFormState: The value that you what the initial form state to be.
  • 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

An array with two values:

  1. The current form state. During the first render, it will match the initialState you passed. After the action is invoked, it’ll match the value returned by the action.
  2. An action that you can pass as the action prop to your form component or as a formAction prop to any button component within the form.

Links

Tagged: React

Leave a comment

Your email address will not be published. Required fields are marked *