C
Genel Bakış
Next.js use cache: React Server Components için Yeni Cache Sistemi

Next.js use cache: React Server Components için Yeni Cache Sistemi

12 Haziran 2025
3 dk okuma süresi
index

Next.js use cache: React Server Components için Yeni Cache Sistemi

Uyarı (Önemli Not)

Bu özellik henüz canary sürümünde bulunuyor. Production ortamında kullanmadan önce stable sürümünü beklemeni öneririm.

Next.js ekibi, React Server Components’in performansını artırmak için güçlü bir yeni özellik geliştirdi: use cache. Bu özellik şu anda canary sürümünde aktif olarak kullanılabiliyor ve yakında stable sürüme geçmesi bekleniyor. Bu yazıda, use cache’in ne olduğunu, nasıl çalıştığını ve neden bu kadar önemli olduğunu kendi deneyimlerimle birlikte anlatacağım.

use cache Nedir?

Not (Kısa Tanım)

use cache, React Server Components’te hesaplama sonuçlarını cache’leyerek performansı artıran yeni bir direktiftir. Client-side’da useMemo veya react cache ile cache’leme yapabiliyorken, server-side’da unstable_cache kullanıyorduk. use cache bu olaya farklı bir bakış açısı getiriyor ve server-side hesaplamaları cache’leme imkanı sunuyor.

Temel Kullanım Örneği

Örnek (Örnek: Okuma Süresi Hesaplama)
'use cache'
 
// Bu fonksiyon cache'lenecek
async function calculateReadingTime(content: string) {
  // Karmaşık hesaplama simülasyonu
  const words = content.split(' ').length
  const readingSpeed = 200 // dakikada kelime sayısı
  const minutes = Math.ceil(words / readingSpeed)
  await new Promise((resolve) => setTimeout(resolve, 100))
  return { minutes, words, readingSpeed }
}
 
export { calculateReadingTime }

Aynı içerik için sadece bir kez çalışır, sonraki çağrılar cache’den döner.

Next.js Cache Sistemi Karşılaştırması

  • Request Memoization: Aynı request içinde tekrar çağrılar cache’lenir.
  • Data Cache: Farklı requestler arası cache’leme (revalidate, force-cache).
  • use cache: Fonksiyon seviyesinde cache’leme, parametrelere göre otomatik anahtar.

Cache Invalidation: Cache’i Nasıl Temizlerim?

Önemli (Cache Invalidation)

Cache’lenmiş verileri güncellemek için revalidateTag kullanabilirsin. Böylece ilgili cache’ler temizlenir ve güncel veriyle tekrar hesaplanır.

Gerçek Dünya Örnekleri

Blog Yazısı İşleme

Örnek (Markdown İşleme)
'use cache'
 
async function processMarkdownContent(content: string) {
  // MDX parsing (yavaş işlem)
  const html = await markdownToHtml(content)
  // İçerik analizi
  const analysis = {
    wordCount: content.split(' ').length,
    readingTime: Math.ceil(content.split(' ').length / 200),
    headings: extractHeadings(content),
    codeBlocks: extractCodeBlocks(content),
  }
  return { html, analysis }
}
 
export { processMarkdownContent }

E-ticaret Ürün Filtreleme

Örnek (Ürün Filtreleme)
'use cache'
 
async function processProductsWithFilters(
  category: string,
  filters: { minPrice?: number; maxPrice?: number; rating?: number },
) {
  // Veritabanından ürünleri al
  const products = await getProductsByCategory(category)
  // Karmaşık filtreleme ve hesaplamalar
  return products
    .filter((product) => {
      if (filters.minPrice && product.price < filters.minPrice) return false
      if (filters.maxPrice && product.price > filters.maxPrice) return false
      if (filters.rating && product.rating < filters.rating) return false
      return true
    })
    .map((product) => ({
      ...product,
      discountedPrice: calculateDiscount(product),
      shippingInfo: calculateShipping(product),
      popularity: calculatePopularity(product),
    }))
    .sort((a, b) => b.popularity - a.popularity)
}
 
export { processProductsWithFilters }

Performans Testi: Önce ve Sonra

Açıklama (Performans Karşılaştırması)
// CACHE OLMADAN - Her seferinde hesaplanıyor
async function calculateWithoutCache(numbers: number[]) {
  console.time('cache-olmadan')
  for (let i = 0; i < 5; i++) {
    await heavyCalculation(numbers)
  }
  console.timeEnd('cache-olmadan')
  // Sonuç: 2.8 saniye
}
 
// CACHE İLE - Sadece ilk seferinde hesaplanıyor
;('use cache')
async function calculateWithCache(numbers: number[]) {
  console.time('cache-ile')
  for (let i = 0; i < 5; i++) {
    await heavyCalculation(numbers) // İlk çağrıdan sonra cache'den
  }
  console.timeEnd('cache-ile')
  // Sonuç: 0.6 saniye (%78 daha hızlı!)
}
 
async function heavyCalculation(data: number[]) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const result = data.reduce(
        (acc, num) => acc + Math.pow(num, 3) + Math.sqrt(num),
        0,
      )
      resolve(result)
    }, 500)
  })
}

Ne Zaman Kullanmalı, Ne Zaman Kullanmamalı?

Ipucu (İdeal Kullanım Alanları)
  • CPU-intensive hesaplamalar (istatistik, analiz)
  • Markdown/MDX parsing işlemleri
  • Kompleks veri dönüşümleri
  • API response’larının işlenmesi
  • Dosya okuma ve parsing işlemleri
Tehlike (Dikkat Edilmesi Gerekenler)
  • Çok sık değişen veriler için kullanma
  • Memory kullanımını takip et
  • Cache invalidation stratejini planla
  • User-specific veriler için dikkatli ol

Pratik Cache Key Stratejileri

Tanım (Cache Key Stratejileri)
  • Parametrelere göre otomatik cache key oluşur
  • Date objesi yerine string kullan (cache key için)
  • Nested cache fonksiyonları ile performans artırılabilir

Sonuç ve Önerilerim

Özet (Özet)

use cache gerçekten güçlü bir özellik. Özellikle server-side hesaplamaları olan projeler için game-changer olacak. Benim deneyimlerime göre:

En büyük faydaları:
  • Server-side cache’leme artık çok kolay
  • CPU-intensive işlemler için %70+ performans artışı
  • Existing Next.js cache sistemiyle mükemmel uyum - Minimal kod değişikliği gerekiyor
Dikkat etmem gerekenler:
  • Memory usage’ı takip etmek kritik
  • Cache invalidation stratejisi önemli
  • User-specific data için extra dikkat
Ipucu (Takip Et)

Next.js’in official documentation sayfasını takip ederek use cache’in stable sürüme geçiş durumunu izleyebilirsin.