ReactJS
How to Use the App Router Effectively in Next.js
Introduction
The App Router in Next.js (introduced in Next.js 13 and refined in Next.js 14 & 15) provides a new way to structure and manage routing. Unlike the Pages Router, the App Router leverages React Server Components (RSCs), server actions, and layouts for a more scalable and optimized experience.
1. Understanding the App Router Structure
In the App Router, you define routes inside the /app directory using folders instead of files. Here's an example:
project-root/
│
├── public/
│ └── favicon.ico
│
├── src/
│ └── app/
│ ├── about/
│ │ ├── error.tsx
│ │ ├── loading.tsx
│ │ └── page.tsx
│ │
│ ├── dashboard/
│ │ ├── layout.tsx
│ │ └── page.tsx
│ │
│ ├── globals.css
│ ├── layout.tsx
│ ├── page.module.css
│ └── page.tsx
2. Leveraging React Server Components (RSCs)
By default, all components in the App Router are Server Components, which means they:
- Reduce JavaScript bundle size
- Fetch data on the server
- Improve SEO and performance
Example of fetching data inside a Server Component:
async function getProducts() {const res = await fetch('https://fakestoreapi.com/products');return res.json();}export default async function ProductsPage() {const products = await getProducts();return (<div><h1>Products</h1><ul>{products.map((product) => (<li key={product.id}>{product.title}</li>))}</ul></div>);}3. Using layout.tsx for Persistent UI
The layout.tsx file helps maintain UI across multiple pages without reloading components (e.g., navigation, sidebar).
export default function RootLayout({children}: {children: React.ReactNode}) {return (<html lang="en"><body><nav>Navbar</nav>{children}</body></html>);}4. Implementing Loading and Error Handling
You can define loading.tsx and error.tsx inside any folder to handle loading states and errors gracefully.
Example: loading.tsx
export default function Loading() {return <p>Loading...</p>;}Example: error.tsx"use client";export default function ErrorPage({error}: {error: Error}) {return <p>Something went wrong: {error.message}</p>;}5. Using Server Actions for Form Handling
Next.js 15 introduces Server Actions, allowing you to mutate data without API routes.
"use server";export async function submitForm(formData: FormData) {const name = formData.get("name");console.log(`Form submitted by: ${name}`);}export default function ContactPage() {return (<form action={submitForm}><input type="text" name="name" required /><button type="submit">Submit</button></form>);}Conclusion
The Next.js App Router makes building modern applications easier by providing:
- Server Components for better performance
- Layouts for persistent UI
- Built-in error handling
- Server Actions for direct form handling
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our ReactJS Expertise.
Comment