Server Actions and Mutations
Server Actions and Mutations ~10 mins - nextjs

Server Actions and Mutations

A Server Action can be defined with the React "use server" directive. You can place the directive at the top of an async function to mark the function as a Server Action, or at the top of a separate file to mark all exports of that file as Server Actions.

Server Components

    // Server Component
export default function Page() {
// Server Action
async function create() {
'use server'

// ...
}

return (
// ...
)
}

Client Components

    'use server'

export async function create() {
// ...
}
    import { create } from '@/app/actions'

export function Button() {
return (
// ...
)
}

You can also pass a Server Action to a Client Component as a prop:

    <ClientComponent updateItem={updateItem} />
    'use client'

export default function ClientComponent({ updateItem }) {
return <form action={updateItem}>{/* ... */}</form>
}