Miscellaneous

import { z } from 'zod' import { useOptimistic } from 'react' import { useFormState } from 'react' import { useActionState } from 'react' import { useFormStatus } from 'react-dom' import { revalidateTag } from 'next/cache' import { revalidatePath } from 'next/cache' import { cookies } from 'next/headers' import { redirect } from 'next/navigation'

This section provides tips on how you can use server actions in conjunction with other React/Next.js features.


Error Handling

When an error occurs, it will be caught by the closest error.js file or <Suspense> boundary on the client side. We suggest using try/catch blocks to capture errors and manage them within your UI.


Optimistic Updates

The React useOptimistic() hook allows you to update the UI optimistically before the Server Action completes, eliminating the need to wait for the response.


Form Validation

For basic client-side form validation, you can use HTML attributes like required and type="email". For more robust server-side validation, consider using a library like Zod to validate form fields before making any data updates. After validating fields on the server, you can return a serializable object in your action and use React's useFormState hook to display messages to the user.


Form State

When you pass the action to useFormState, the action's function signature changes to receive a new prevState or initialState parameter as the first argument. Since useFormState is a React hook, it must be used within a Client Component. Then, pass your action to the useFormState hook and use the returned state to display error messages if needed.


Pending

The useFormStatus hook also provides a pending boolean, which you can use to show a loading indicator while the action is being processed.


Cache Revalidation

You can refresh the Next.js cache within your Server Actions using the revalidatePath() API. Alternatively, you can invalidate a specific data fetch by using a cache tag with revalidateTag().


Cookies

You can use the cookies API within a Server Action to get, set, and delete cookies.


Redirection

To redirect the user to a different route after a Server Action completes, use the redirect API. Make sure to call redirect outside of the try/catch block.