Server Actions — Handle Mutations Directly Without API Routes
Server Actions — Handle Mutations Directly Without API Routes
💡 Why Learn This? — The End of the 'Form Submit = API Route + fetch + useState' Era
'use server' · formAction · revalidatePath · useActionState
1. Two Placements for 'use server'
Use inline only for short functions. Typically, extract them into a separate file.
2. Signature of
💡 💡 5 Server Actions Best Practices
1. Always revalidate after a mutation
Forgetting this is the #1 cause of the "I posted something but it doesn't show up" bug.
2. Pass IDs via argument binding
ID goes in the first argument, formData in the second. No need for hidden inputs.
3. useActionState is the React 19 standard (replaces the old useFormState)
The old useFormState (react-dom) is deprecated.
4. Calling redirect() inside a Server Action is fine
Like a throw, it terminates the flow — code after it does not execute.
5. Security — Input validation is required inside Server Actions too
Even if the client validates the form, someone can send a direct POST request. Validate inside the action with something like zod: