Course contentsShow
← React
Lesson 1487 of 2,39637. React 19 and BeyondFree lesson

Error Handling in Actions

Returning error states from action functions and displaying validation or network errors to users.

Error Handling in Actions

What you'll learn: How to capture and display errors from action functions so users know when something goes wrong.

The Problem Actions Solve

When you submit a form or perform an async action with useActionState, things can fail—network errors, validation problems, database issues. Without proper error handling, users are left confused, staring at a spinning button that never resolves.

Returning Error States from Actions

Your action function can return any state shape you want, including error information. The common pattern is returning an object with both data and error fields:

async function createPost(prevState, formData) {
  try {
    const title = formData.get('title');
    
    // Validation error
    if (!title || title.length < 3) {
      return { error: 'Title must be at least 3 characters', data: null };
    }

    // Network request
    const response = await fetch('/api/posts', {
      method: 'POST',
      body: JSON.stringify({ title })
    });

    if (!response.ok) {
      return { error: 'Failed to create post', data: null };
    }

    const post = await response.json();
    return { error: null, data: post };
  } catch (err) {
    return { error: err.message, data: null };
  }
}

Displaying Errors to Users

In your component, check the state for errors and show them conditionally:

const [state, submitAction, isPending] = useActionState(createPost, { error: null, data: null });

return (
  <form action={submitAction}>
    <input name="title" />
    {state.error && <p className="error">{state.error}</p>}
    <button disabled={isPending}>Submit</button>
  </form>
);

Key Takeaway: Return error information from your action functions as part of the state object, then conditionally render those errors in your UI—this gives users immediate, actionable feedback when operations fail.