Server Actions, Form Mutations & Optimistic UI
Server Actions are asynchronous functions defined with the 'use server' directive that execute on the server. They can be invoked directly from HTML forms, event handlers, or Client Components, eliminating the need to write manual REST or GraphQL API route handlers for data mutations.
Server Actions seamlessly integrate with React 19 hooks like useActionState and useOptimistic. useOptimistic allows the UI to render immediate state updates before the server mutation completes, rolling back automatically if the server request fails.
Exercise
Create a Server Action that receives form data, validates the inputs, inserts a database record, and purges the page cache with revalidatePath.
Check your understanding
Where must the 'use server' directive be placed?Show answerHide answer
Answer
At the top of a dedicated server actions file, or at the top of an individual async function inside a Server Component.What advantage does form action={serverAction} offer for user experience?Show answerHide answer
Answer
Progressive enhancement: forms can submit even before client JavaScript has fully downloaded and hydrated.