Next.js Example

Next.js Pages

Building pages and components in Next.js

Page Basics

Creating pages and components in Next.js

Basic Page Component

// pages/index.tsx
import Head from 'next/head'

function HomePage() {
  return (
    
Welcome to Next.js

Welcome

This is a Next.js page.

) } export default HomePage

Custom Layout

// components/Layout.tsx
function Layout({ children }) {
  return (
    
{children}
{/* Footer content */}
) } export default Layout

Key Points

  • Pages are React components exported from pages directory
  • Supports both default and named exports
  • Built-in support for TypeScript (.tsx)
  • Automatic code splitting per page

Data Fetching

Methods for fetching data in Next.js pages

Static Site Generation (SSG)

// pages/posts/[id].tsx
function Post({ post }) {
  return (
    

{post.title}

{post.content}
) } export async function getStaticProps({ params }) { const post = await getPost(params.id) return { props: { post } } } export async function getStaticPaths() { const posts = await getPosts() const paths = posts.map((post) => ({ params: { id: post.id } })) return { paths, fallback: false } } export default Post

Server-Side Rendering (SSR)

// pages/profile.tsx
function Profile({ user }) {
  return (
    

Welcome {user.name}

Role: {user.role}

) } export async function getServerSideProps(context) { const session = await getSession(context) const user = await fetchUser(session.userId) return { props: { user } } } export default Profile

Key Points

  • getStaticProps for static data fetching
  • getServerSideProps for dynamic SSR
  • getStaticPaths for dynamic routes
  • Incremental Static Regeneration (ISR)

Optimizations

Performance optimizations for Next.js pages

Image Optimization

import Image from 'next/image'

function ProductCard({ product }) {
  return (
    
{product.name}

{product.name}

{product.description}

) }

Dynamic Imports

import dynamic from 'next/dynamic'

const DynamicChart = dynamic(() => import('../components/Chart'), {
  loading: () => 

Loading chart...

, ssr: false // Disable server-side rendering }) function Dashboard() { return (

Analytics Dashboard

) }

Key Points

  • Automatic image optimization
  • Code splitting with dynamic imports
  • Built-in performance analytics
  • Automatic font optimization