Web Development

Next.js basics

Next.js is a React framework that adds file-based routing, server-side rendering, and a great developer experience out of the box.


File-based Routing

In Next.js App Router, every folder inside app/ with a page.tsx file becomes a route. The folder name is the URL path.

app/
page.tsx → /
about/
page.tsx → /about
blog/
[slug]/
page.tsx → /blog/:slug

Dynamic Routes

Wrap a folder name in square brackets to create a dynamic segment. The segment value is passed as a prop to the page component.

export default function BlogPost({ params }: { params: { slug: string } }) {
return <h1>Post: {params.slug}</h1>
}

Server and Client Components

By default, all components in the App Router are Server Components — they run on the server and send HTML to the browser. Add 'use client' at the top of a file to opt into client-side rendering.

'use client'
import { useState } from 'react'
export default function Toggle() {
const [on, setOn] = useState(false)
return <button onClick={() => setOn(!on)}>{on ? 'On' : 'Off'}</button>
}

Fetching Data

Server Components can fetch data directly with async/await. No useEffect needed.

async function getPosts() {
const res = await fetch('https://api.example.com/posts')
return res.json()
}
export default async function BlogPage() {
const posts = await getPosts()
return (
<ul>
{posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
)
}
Previous
React fundamentals