WhoBuilt

Enhancing Forms with React Server Components

Oct 4, 2024· 24 min· 812 views·Watch on YouTube

Speaker

Aurora Scharff, a web developer and consultant at Inmeta, demonstrates practical form patterns with React Server Components at React Universe Conf 2024, hosted by Callstack.

Start with a server action

Scharff’s example uses the Next.js App Router, Prisma, and a local database. She connects a form’s action property to a server action that creates a message, then uses Next.js revalidatePath to refresh the displayed messages. The basic submission works without client JavaScript.

Validate input and return errors

Scharff validates submitted data with Zod, checking that message content is present and the data has the expected structure. She shows that invalid data can throw an error caught by an error boundary, or return a structured error state for the form to display. Her example also limits each user to five messages.

Add feedback with React hooks

The useActionState hook carries the server action’s result into the form, enabling an error message or toast. Scharff preserves submitted content after an error and uses the pending state to disable the button and show that a submission is underway. She keeps a no-script fallback so errors remain visible without JavaScript.

Reuse pending feedback

Scharff extracts the submit control into a reusable SubmitButton that reads the parent form’s status with useFormStatus. The same component can show a spinner in different forms, including a reset form whose server action deletes messages and revalidates the page.

Offer optimistic updates

With useOptimistic, Scharff displays a message immediately with a sending state while the server processes it. The server response replaces the optimistic state, and messages that fail the server-side limit are rolled back. She presents this as an optional enhancement based on application needs.

Takeaways

  • Use server actions for forms that should submit before client JavaScript loads.
  • Validate all client-submitted data on the server, and return structured errors when users can recover from them.
  • Use useActionState to connect server results and pending feedback to a form.
  • Extract useFormStatus feedback into a reusable component for multiple forms.
  • Use optimistic updates when immediate feedback helps, while accounting for server failures and rollback.

Mentioned in this talk

Search inside this talk

What was claimed 10

Related talks