available for work
Current position: Front End Lead @Réfugiés.info

Next.js 14 App Router: A Comprehensive Guide

frontend

An in-depth look at the new App Router in Next.js 14 and how to leverage its features for better performance and developer experience.

Language:
EnglishFrançais

Mastering Next.js 14 App Router

The introduction of the App Router in Next.js 14 represents a significant evolution in how we think about routing and data fetching in React applications. In this comprehensive guide, we'll explore its key features and best practices.

Why App Router?

The new App Router offers several advantages over the traditional Pages Router:

  • Server Components by Default: Better performance and smaller client bundles
  • Nested Layouts: More intuitive UI composition
  • Simplified Data Fetching: Built-in support for async components
  • Improved Loading States: Built-in loading.js and error.js conventions

Key Concepts

1. File-system Based Routing

app/
  (marketing)/
    page.tsx        // Marketing page
    layout.tsx      // Marketing layout
  dashboard/
    page.tsx        // Dashboard page
    layout.tsx      // Dashboard layout
    settings/
      page.tsx      // Nested route

2. Server and Client Components

Next.js 14 makes it easy to mix server and client components:

// app/components/ServerComponent.tsx
export default async function ServerComponent() {
  const data = await fetchData();
  return <div>{data}</div>;
}

// app/components/ClientComponent.tsx
'use client';

export default function ClientComponent() {
  const [state, setState] = useState();
  return <div>Interactive Component</div>;
}

Performance Optimization

1. Streaming

import { Suspense } from 'react';
import { LoadingSkeleton } from './loading';

function Page() {
  return (
    <div>
      <Suspense fallback={<LoadingSkeleton />}>
        <HeavyComponent />
      </Suspense>
    </div>
  );
}

2. Data Fetching

async function getData() {
  const res = await fetch('https://api.example.com/data', {
    next: { revalidate: 3600 } // Revalidate every hour
  });
  return res.json();
}

export default async function Page() {
  const data = await getData();
  return <div>{data}</div>;
}

Best Practices

  1. Colocate Components: Keep components close to their routes
  2. Use Route Groups: Organize routes with parentheses (e.g., (marketing))
  3. Leverage Loading States: Implement loading.js for better UX
  4. Optimize Images: Use the next/image component with modern formats
  5. Implement ISR: Use revalidate for incremental static regeneration

Conclusion

The App Router in Next.js 14 provides a more intuitive and powerful way to build modern web applications. By understanding its core concepts and following best practices, you can create highly performant and maintainable applications.

Have you tried the new App Router? Share your experiences in the comments!