Tutorials/NextJS/Getting Started
Lesson

Fetching Data

Getting Started/NextJS

Next.js Fetching Data (Easy Notes)

📌 1. Fetching Data kya hota hai?

👉 Data lena from:

  • API

  • Database

  • Backend


🖥️ 2. Server Component me Data Fetch

👉 Best method ✅
👉 Fast + Secure


🔹 Example (API se data fetch)

plaintext
export default async function Page() {
  const res = await fetch("https://api.vercel.app/blog")
  const posts = await res.json()

  return (
    <ul>
      {posts.map((post) => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  )
}

💡 Important Points

  • Server Component me:

    • async/await use kar sakte ho

    • direct DB call kar sakte ho

  • Same fetch auto optimize hota hai (duplicate calls avoid)


🛢️ Database se Fetch (Safe 🔐)

plaintext
import { db } from "@/lib/db"

export default async function Page() {
  const data = await db.getAll()
  return <div>{data.length}</div>
}

👉 API key client me expose nahi hoti


⚡ 3. Streaming kya hota hai?

👉 Simple:


  • Page ko parts me load karna


  • Fast UI show karna


🔹 Method 1: loading.js

📁 Folder:

plaintext
app/blog/
   page.js
   loading.js
plaintext
export default function Loading() {
  return <p>Loading...</p>
}

👉 User ko turant loading dikhega


🔹 Method 2: Suspense (Best)

plaintext
import { Suspense } from "react"

export default function Page() {
  return (
    <div>
      <h1>Blog</h1>

      <Suspense fallback={<p>Loading...</p>}>
        <BlogList />
      </Suspense>
    </div>
  )
}

👉 Partial loading possible


💻 4. Client Component me Data Fetch

🔹 Method 1: use() API

plaintext
// Server
const posts = getPosts()

<Suspense fallback="Loading...">
  <Posts posts={posts} />
</Suspense>
plaintext
"use client"
import { use } from "react"

export default function Posts({ posts }) {
  const data = use(posts)

  return <div>{data.length}</div>
}

🔹 Method 2: SWR (npm use)

plaintext
npm install swr
plaintext
"use client"
import useSWR from "swr"

const fetcher = (url) => fetch(url).then(res => res.json())

export default function Page() {
  const { data, error } = useSWR("/api/data", fetcher)

  if (!data) return "Loading..."
  if (error) return "Error"

  return <div>{data.length}</div>
}

🔄 5. Sequential vs Parallel Fetch

❌ Sequential (Slow)

plaintext
const a = await getA()
const b = await getB()

👉 ek ke baad ek


✅ Parallel (Fast)

plaintext
const aPromise = getA()
const bPromise = getB()

const [a, b] = await Promise.all([aPromise, bPromise])

👉 dono ek saath start


🧠 6. Important Rules (Interview)


  • Data fetch Server Component me karo (best)


  • Client me only when needed


  • Streaming → performance improve


  • Suspense → loading UI control


  • Parallel fetch → fast


🔥 Short Revision (1 min)

👉 Server = best for data

👉 Client = UI interaction

👉 Suspense = loading control

👉 Promise.all = fast fetch

👉 npm = swr install


💥 Super Simple Line

👉 "Next.js me data server pe fetch karo aur UI client pe handle karo"