Skip to content
Data & CachingChapter 15 / 34Advanced5 min read

Cache Components & use cache

Next.js use cache aur Cache Components ka naya caching model, cacheLife aur cacheTag ke saath pages, components aur functions cache karna seekhein.

On this page

1. Cache Components kya hai?

Next.js 16 mein sab kuch by default dynamic hai, yani har request par chalta hai. Jo hissa cache karna ho, us par aap khud "use cache" likhte hain. Compiler arguments aur captured values se cache key khud bana leta hai.

Yeh model Partial Prerendering (PPR) ko bhi complete karta hai: page ka static aur cached hissa ek static shell ban jata hai, aur dynamic hissa <Suspense> ke andar stream hota hai.

2. Kyun zaroori hai?

Purane App Router mein caching implicit thi. fetch khud cache ho jata tha aur developers confuse rehte the ke data purana kyun dikh raha hai.

Purana implicit cachingCache Components
fetch khud cache ho jata thaKuch bhi cache nahi jab tak aap na kahein
Route segment config ka jungleEk directive: use cache
Poora route static ya dynamicEk hi page mein static, cached aur dynamic hisse
Cache key samajhna mushkilCompiler arguments se key banata hai
Expiry ke liye revalidate numbercacheLife profiles jaise hours, days, max

3. Kahan use hota hai?

Use caseKya cache kareinProfile
Blog posts listComponent ya data functionhours ya max
Product cataloggetProducts() functionhours
CMS pagesPoora page, cacheTag ke saathmax
Exchange ratesData functionminutes
User cartCache na karein, Suspense mein streamKoi nahi

4. Kaise kaam karta hai?

use cache ka flow
next.config.ts mein cacheComponents true
Function ya component mein use cache
Arguments se cache key banti hai
Pehli baar result compute aur store
Agli request par cache se result
cacheLife ke mutabiq refresh

"use cache" teen level par lagta hai:

LevelKaiseAsar
FileFile ki pehli line par "use cache"File ke saare exported functions cache
ComponentComponent body ki pehli lineComponent ka rendered output cache
FunctionAsync function body ki pehli lineFunction ka return value cache

5. Code example

Step 1: Config enable karein

ts
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  cacheComponents: true,
};

export default nextConfig;

Step 2: Data function aur component cache karein

tsx
import { Suspense } from "react";
import { cookies } from "next/headers";
import { cacheLife, cacheTag } from "next/cache";

async function getProducts() {
  "use cache";
  cacheLife("hours");
  cacheTag("products");

  const res = await fetch("https://api.example.com/products");
  return res.json() as Promise<{ id: string; name: string }[]>;
}

async function ProductList() {
  const products = await getProducts();

  return (
    <ul>
      {products.map((product) => (
        <li key={product.id}>{product.name}</li>
      ))}
    </ul>
  );
}

async function CartCount() {
  const cartId = (await cookies()).get("cart")?.value;
  return <p>Cart: {cartId ? "items hain" : "khaali"}</p>;
}

export default function ShopPage() {
  return (
    <main>
      <h1>Shop</h1>
      <ProductList />
      <Suspense fallback={<p>Cart load ho raha hai...</p>}>
        <CartCount />
      </Suspense>
    </main>
  );
}

Code kaise kaam kar raha hai?

CheezMatlab
cacheComponents: trueNaya caching model on
"use cache"getProducts ka result cache hota hai
cacheLife("hours")Result kitni der fresh rahe, built-in profile
cacheTag("products")Tag jis se baad mein on-demand invalidate kar saktay hain
<h1> aur ProductListStatic shell ka hissa, fauran milte hain
CartCountcookies() runtime data hai, is liye Suspense mein stream

Built-in cacheLife profiles: seconds, minutes, hours, days, weeks, max. Agar profile na dein to default lagta hai. Aap object bhi de saktay hain: cacheLife({ stale: 300, revalidate: 3600, expire: 86400 }).

Interview tip

"use cache" ke andar cookies() ya headers() seedha nahi parh sakte. Runtime value bahar parhein aur argument ke taur par cached function ko dein, value khud cache key ka hissa ban jati hai.

6. Common mistakes

Galati: cacheComponents enable kiye baghair use cache likhna

Why? Directive ka naya model config flag ke baghair kaam nahi karta aur build error deta hai.

Behtar: next.config.ts mein cacheComponents true set karo, phir use cache lagao.

Galati: use cache ke andar cookies ya headers parhna

Why? Cached result sab users mein share hota hai, is liye runtime data andar allowed nahi.

Behtar: Cookie value bahar parho aur cached function ko argument ke taur par pass karo.

Galati: User specific data ko shared cache mein dalna

Why? Ek user ka data doosre user ko dikh sakta hai, yeh security bug hai.

Behtar: Personal data ko Suspense ke andar uncached rakho ya user id ko cache key ka hissa banao.

Galati: cacheLife ke baghair har jagah use cache lagana

Why? Default profile lagta hai jo shayad aapke data ke liye munasib na ho.

Behtar: Har use cache ke saath cacheLife ka sahi profile likho.

7. Pehle aur baad mein kya seekhein?

Final quick revision

PointDetail
Enable kaisecacheComponents: true in next.config.ts
Cache kaise"use cache" file, component ya function level par
Kitni dercacheLife("hours") ya custom object
TagcacheTag("products") on-demand invalidation ke liye
Runtime data<Suspense> mein stream, cache ke bahar