InterviewHubPRO
Section Overview
Q320

Question 320 of 445

Part 10: Modern React 18, React 19 & Next.js Patterns (317 - 353)

72%
React & Modern Frontend (445 Qs)•Part 10: Modern React 18, React 19 & Next.js Patterns (317 - 353)

What are Server Actions in React 19?

Server Actions allow you to call server-side functions directly from client components without writing API endpoints.

Basic Server Action

jsx
// app/actions.js
'use server'

export async function createPost(formData) {
const title = formData.get('title');
const content = formData.get('content');

const post = await db.posts.create({
  title,
  content,
  userId: await getCurrentUser()
});

revalidatePath('/posts');
redirect(`/posts/${post.id}`);
}

Using in Forms

jsx
// app/new-post.jsx
import { createPost } from './actions';

export default function NewPost() {
return (
  <form action={createPost}>
    <input name="title" required />
    <textarea name="content" required />
    <button type="submit">Create Post</button>
  </form>
);
}

With useFormState for Loading States

jsx
'use client'
import { useFormState } from 'react-dom';
import { createPost } from './actions';

export default function NewPost() {
const [state, formAction] = useFormState(createPost, { message: '' });

return (
  <form action={formAction}>
    <input name="title" required />
    <textarea name="content" required />
    <button type="submit">Create Post</button>
    {state.message && <p>{state.message}</p>}
  </form>
);
}

Progressive Enhancement

Server Actions work even if JavaScript is disabled!

jsx
// This form works without JavaScript
<form action={serverAction}>
<input name="email" type="email" />
<button>Subscribe</button>
</form>

Security

  • Automatically CSRF protected
  • Always run on server (never exposed to client)
  • Can use server-only packages safely