1. Next JS - Introduction

Ayush RajputAyush Rajput
2 min read
  1. What is NextJS ?

    Next.js is a React framework that allows you to build fast, scalable web applications with features like:

    • Server-side rendering (SSR)

    • Static site generation (SSG)

    • API routes for serverless functions

    • Automatic code splitting

    • Fast Refresh for development

  1. Setting up NextJS project

    Step 1 : Create NextJs app

     npx create-next-app@latest my-next-app  // This will generate a new Next.js project called my-next-app after given answer to some questions
    

    Step 2: Navigate to Your Project

     cd my-next-app
    

    Step 3: Start the Development Server

     npm run dev
    
  1. What is server component ?

    A Server Component runs only on the server. It is rendered on the server, and the result (HTML) is sent to the client. It cannot use browser-only features like useState, useEffect, localStorage, or event listeners.

    When to use:

    • Fetching data from a database or API

    • Heavy computation or sensitive logic

    • You don't need interactivity (like forms, click events)

✅ By default, all components in the /app directory are Server Components.

// app/page.js (or .tsx)
export default function Home() {
  return <h1>Hello from Server Component</h1>;
}
  1. What is client component ?

    A Client Component runs in the browser. It supports interactivity, state, effects, and all browser APIs. You have to explicitly mark it using 'use client'.

    ✅ When to use:

    • useState, useEffect, useRef, and other react hooks

    • Event handling (onClick, onChange, etc.)

    • DOM manipulation

    • Third-party libraries that depend on the DOM

use client must be the first line in the file to mark it as a client component.

    'use client';

    import { useState } from 'react';

    export default function Counter() {
      const [count, setCount] = useState(0);
      return (
        <div>
          <p>Count: {count}</p>
          <button onClick={() => setCount(count + 1)}>Increment</button>
        </div>
      );
    }
  1. Folder Directory Structure

my-next-app/
├── app/
│   ├── page.js         --> Home route ('/')
│   ├── about/
│   │   └── page.js     --> About route ('/about')
│   ├── blog/
│   │   ├── page.js     --> Blog listing ('/blog')
│   │   └── [slug]/
│   │       └── page.js --> Dynamic route like '/blog/my-post'
│   ├── layout.js       --> Shared layout for all routes
│   └── globals.css     --> Global CSS
├── public/             --> Static assets (images, etc.)
├── styles/             --> Optional extra styles
├── next.config.js      --> Config file
├── package.json
0
Subscribe to my newsletter

Read articles from Ayush Rajput directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ayush Rajput
Ayush Rajput