⚡ TECH BLOG
Home
Blog
Tags
About
⚡

Powered by Next.js 15 & Modern Web Tech ⚡

Back to Home

Next.js 14: Server Actions and Performance

October 15, 2023
nextjsreactjavascriptwebdev
Next.js 14: Server Actions and Performance

Next.js 14: Server Actions and Performance

Next.js 14 brings Server Actions to stable, improved performance, and new features.

Server Actions (Stable)

// app/actions.ts
'use server';

import { revalidatePath } from 'next/cache';

export async function createTodo(formData: FormData) {
  const title = formData.get('title');
  
  await db.todo.create({ data: { title } });
  
  revalidatePath('/todos');
}

Using Server Actions

// app/todos/page.tsx
import { createTodo } from '../actions';

export default function Todos() {
  return (
    <form action={createTodo}>
      <input name="title" type="text" required />
      <button type="submit">Add Todo</button>
    </form>
  );
}

useFormStatus Hook

import { useFormStatus } from 'react-dom';

function SubmitButton() {
  const { pending } = useFormStatus();
  
  return (
    <button type="submit" disabled={pending}>
      {pending ? 'Submitting...' : 'Submit'}
    </button>
  );
}

useFormState Hook

import { useFormState } from 'react-dom';

function Form() {
  const [state, formAction] = useFormState(submitForm, null);
  
  return (
    <form action={formAction}>
      {state?.error && <p>{state.error}</p>}
      <input name="email" type="email" />
      <button type="submit">Subscribe</button>
    </form>
  );
}

Partial Prerendering

// experimental in Next.js 14
export const experimental_ppr = true;

export default function Page() {
  return (
    <main>
      <h1>Static content</h1>
      <Suspense fallback={<Loading />}>
        <DynamicContent />
      </Suspense>
    </main>
  );
}

Improved Metadata

import { Metadata } from 'next';

export const metadata: Metadata = {
  title: {
    template: '%s | My Site',
    default: 'My Site',
  },
  openGraph: {
    title: 'My Site',
    description: 'Welcome to my site',
  },
};

Conclusion

Next.js 14 makes building full-stack React applications easier with stable Server Actions and performance improvements.

Share:

💬 Comments