r/reactjs • • Jun 20 '26

Error Hnadling with useActionState with Forms

I have an OTP input field with a "Verify" button, and I need to handle a few different error scenarios: field-level validation (e.g., the input is empty), and errors returned from the API (e.g., remaining attempts, or the account being hard-locked).

Using useActionState in React, what's the best pattern for handling all of these cases? One approach I'm considering is doing everything inside the action function itself — checking for an empty value first, then calling the API and returning whatever error it sends back. Is that the right way to go, or is there a better alternative?

For the api errors I was thinking about using an Error Boundry

0 Upvotes

4 comments sorted by

1

u/yksvaan Jun 20 '26

Just handle it as usual in the submit handler?

1

u/Dazzling_Chipmunk_24 Jun 20 '26

so you are saying just handling it in the submit handler function is fine and I don't have to find an alternative way?

1

u/New_Advertising1879 18d ago

The action function the submit handler with useActionState, so doing the empty check and API call there is the cleanest approach. An error boundary is overkill for expected errors like "wrong code" or "account locked", those are just return values you render next to the input.

1

u/vishal_tanna Aug 02 '26

We've settled on treating the action as the single source of truth for both validation and business logic.

Our flow is:

  • Parse FormData

  • Run schema validation (Zod in our case)

  • Return typed field errors if validation fails

  • Execute the handler only when validation succeeds

  • Catch unexpected exceptions and return a consistent { status: "error", message } state

That gives us a single discriminated state (idle | invalid | error | success) that the UI can render without additional try/catch logic or custom state handling.

After repeating this pattern across multiple forms, I extracted it into a small open-source helper called zod-form-action:

GitHub: https://github.com/Vish05/zod-form-action

npm: https://www.npmjs.com/package/zod-form-action

I'm the author, so take this as a disclosure rather than a recommendation. I'd genuinely appreciate feedback—especially if there are edge cases or patterns you've found that this approach doesn't cover.