Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readReact

Handle form errors with useActionState

Return field errors from a React form action and keep the submitted input available for a retry.

Give a display-name form a way to show validation errors beside the field. With useActionState, you can render the action's result and keep the typed name available for a retry.

Return the validation error

With useActionState, a form action can return a result that the component renders. The hook passes the previous result first and the submitted FormData second. If you give the wrapped action to <form action>, React handles that dispatch when the form submits.

Use the same result shape for the empty state, a validation failure and a successful submit. That gives the component a place to render the error and lets a successful retry clear it. This example accepts the name in memory so you can try both outcomes.

import { useActionState, useId, useState } from 'react'

async function validateName(_previous, formData) {
  const name = String(formData.get('name') ?? '').trim()

  if (name.length < 3) {
    return { error: 'Use at least three characters.', accepted: '' }
  }

  return { error: '', accepted: name }
}

export default function NameForm() {
  const errorId = useId()
  const [name, setName] = useState('')
  const [result, action, pending] = useActionState(validateName, {
    error: '',
    accepted: '',
  })

  return (
    <form action={action}>
      <label>
        Display name
        <input
          name="name"
          value={name}
          onChange={(event) => setName(event.target.value)}
          aria-invalid={Boolean(result.error)}
          aria-describedby={result.error ? errorId : undefined}
        />
      </label>
      {result.error && <p id={errorId} role="alert">{result.error}</p>}
      <button disabled={pending}>Check name</button>
      <p role="status">{result.accepted && `Accepted: ${result.accepted}`}</p>
    </form>
  )
}

Submit Al and the error appears with Al still in the input. Submit Ali to clear the error and see Accepted: Ali. The error ID comes from useId so each form instance describes its own field.

Keep the input available for a retry

React resets uncontrolled form fields when a form action succeeds. Returning an error object counts as a normal return. The controlled input above keeps its value in name, so the user can fix the two letters they typed. If you want a blank field after acceptance, clear that state on the successful path.

Return validation messages for mistakes the user can correct. An exception from the action reaches the nearest error boundary and may replace the form. For a real save, return the field error from the validation step and return the accepted name after the write succeeds. That keeps the success message tied to the write.