Advertisement
Intermediate React, Server Actions & Data Mutations

What is a server action in React and what problem does it solve?

Short answer

A server action is a function that runs directly on the server but can be called from a component as if it were a normal function, letting a form submit data and update a database without needing to manually build a separate API endpoint or write client side fetch code.

Save React mock interview
Advertisement
AModel answer
A server action is a function that runs directly on the server but can be called from a component as if it were a normal function, letting a form submit data and update a database without needing to manually build a separate API endpoint or write client side fetch code.
// A server action, marked with 'use server'
async function createPost(formData) {
  'use server';
  await db.posts.create({ title: formData.get('title') });
}

function NewPostForm() {
  return (
    <form action={createPost}>
      <input name="title" />
      <button type="submit">Create Post</button>
    </form>
  );
}
Real-world example
A blogging platform lets writers publish a new post by submitting a form directly to a server action, skipping the need to build and call a separate API route just to save the post to the database.
Likely follow-ups
  • How does a server action differ from a traditional API route in terms of how you write it?
  • What security considerations apply when writing a server action?
Related topics