Day 96

Next.js Introduction

14 min
JavaScript 100 Days

Next.js React ke upar bana full-stack framework hai — file-based routing, Server Side Rendering, Static Generation, API routes sab built-in. Is course ki website Next.js mein bani hai!

App Router File Structure

Next.js App Router ka file-based routing.

structure.ts
typescript
// Next.js App Router structure:
// app/
// ├── page.tsx          → /
// ├── layout.tsx        → root layout
// ├── about/
// │   └── page.tsx      → /about
// ├── blog/
// │   ├── page.tsx      → /blog
// │   └── [slug]/
// │       └── page.tsx  → /blog/any-slug
// └── api/
//     └── users/
//         └── route.ts  → /api/users

// page.tsx — Server Component by default
export default function AboutPage() {
  return <h1>About Us</h1>;
}

// Dynamic route — same as our lesson pages!
export default async function BlogPost({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  // fetch data based on slug
  return <article>Post: {slug}</article>;
}

// Metadata
export const metadata = {
  title: "About — My App",
  description: "Learn about us",
};

Server vs Client Components

When to use 'use client'.

components.tsx
tsx
// Server Component (default) — no "use client"
// - Can fetch data directly
// - Smaller bundle
// - No useState/useEffect
async function ProductList() {
  const products = await fetch("https://api.example.com/products")
    .then(r => r.json()); // Direct DB/API call!
  
  return (
    <ul>
      {products.map(p => <li key={p.id}>{p.name}</li>)}
    </ul>
  );
}

// Client Component — "use client" zaroor
"use client";
import { useState } from "react";

function LikeButton({ initialLikes }: { initialLikes: number }) {
  const [likes, setLikes] = useState(initialLikes);
  
  return (
    <button onClick={() => setLikes(l => l + 1)}>
      ❤️ {likes}
    </button>
  );
}

🎯 Practice Challenge

Next.js project banao — pages: Home, About, Blog (list), Blog Detail (dynamic). Server Components se data fetch karo.