basically a POST
Request that return both the updated UI and new data in a single server roundtrip.
Exclusive run on the server, can be used by both server & client components.
used for fetching or mutating data on the server.
defined with the React "use server"
directive.
place directive at the top of an async
function(inline function level directive) OR at the top of a separate file to mark all exports of that file as Server Actions(module level directive).
async function create() { // inline function level directive
'use server'
// Mutate data
}
OR
actions.ts
'use server' // module level directive
export async function create() {}
Server Components: can use either the inline function level or module level directive.
Client Components: can ONLY use module level directive. create a new file to create actions and export functions from there.
Server Actions can be passed as props to a client component i.e <ClientComponent updateItemAction={updateItem} />
, remember regular functions can't be passed as props because they can’t be serialized across client-server boundaries.
Can be invoked with <form>
, useEffect
, event handlers (onClick, onChange, etc.), third-party libraries (React Query, SWR), and other form elements like <button>
.
Arguments & Return Values of Server Actions must be Serializable. Primitives, Array, Plain Object, etc are Serializable. JSX/React Elements, functions (that are not server actions), classes, etc are not serializable.
action
prop. i.e - <form action={submitFeedback}>