W serwerowniach Metropolii Quantum 2150, gdzie każda milisekunda ma znaczenie, poznasz rewolucyjne API cachowania wprowadzone w Next.js 15. Dyrektywa
use cache zastępuje przestarzałe unstable_cache i wprowadza znacznie bardziej intuicyjny sposób zarządzania pamięcią podręczną.use cache to nowa dyrektywa (podobna do use server czy use client), która oznacza funkcje lub całe pliki jako cachowalne. Next.js automatycznie zarządza cyklem życia cache i rewalidacją.Aby korzystać z
use cache, musisz najpierw włączyć eksperymentalną flagę dynamicIO:1// next.config.js
2module.exports = {
3 experimental: {
4 dynamicIO: true,
5 },
6};1// app/lib/data.ts
2async function getProducts() {
3 'use cache';
4
5 const response = await fetch('https://api.quantum-store.com/products');
6 return response.json();
7}1// app/lib/cached-data.ts
2'use cache';
3
4export async function getUsers() {
5 const response = await fetch('https://api.quantum-store.com/users');
6 return response.json();
7}
8
9export async function getOrders() {
10 const response = await fetch('https://api.quantum-store.com/orders');
11 return response.json();
12}Funkcja
cacheLife pozwala precyzyjnie określić, jak długo dane powinny być przechowywane w cache.Next.js dostarcza wbudowane profile czasowe:
1import { cacheLife } from 'next/cache';
2
3async function getNews() {
4 'use cache';
5 cacheLife('minutes'); // cache na kilka minut
6
7 return fetch('https://api.quantum-news.com/latest').then(r => r.json());
8}
9
10async function getStaticContent() {
11 'use cache';
12 cacheLife('days'); // cache na dni
13
14 return fetch('https://api.quantum-cms.com/static').then(r => r.json());
15}
16
17async function getRealTimeData() {
18 'use cache';
19 cacheLife('seconds'); // cache na sekundy
20
21 return fetch('https://api.quantum-sensors.com/data').then(r => r.json());
22}| Profil | stale | revalidate | expire | Opis | |--------|-------|------------|--------|------| |
seconds | - | 1s | 60s | Dla szybko zmieniających się danych |
| minutes | 5min | 1min | 1h | Dla danych aktualizowanych co kilka minut |
| hours | 5min | 1h | 1d | Dla danych godzinowych |
| days | 5min | 1d | 1w | Dla rzadko zmienianych danych |
| weeks | 5min | 1w | 30d | Dla prawie statycznych danych |
| max | 5min | 30d | 1y | Maksymalny czas cache |Możesz definiować własne profile w
next.config.js:1// next.config.js
2module.exports = {
3 experimental: {
4 dynamicIO: true,
5 cacheLife: {
6 quantumFast: {
7 stale: 10, // sekundy - czas gdy dane są "świeże"
8 revalidate: 30, // sekundy - czas po którym rewalidacja w tle
9 expire: 300, // sekundy - maksymalny czas życia
10 },
11 quantumProducts: {
12 stale: 60,
13 revalidate: 300,
14 expire: 3600,
15 },
16 },
17 },
18};Użycie własnego profilu:
1import { cacheLife } from 'next/cache';
2
3async function getQuantumProducts() {
4 'use cache';
5 cacheLife('quantumProducts');
6
7 return fetch('https://api.quantum-store.com/products').then(r => r.json());
8}Możesz też definiować konfigurację bezpośrednio:
1import { cacheLife } from 'next/cache';
2
3async function getCriticalData() {
4 'use cache';
5 cacheLife({
6 stale: 5,
7 revalidate: 15,
8 expire: 60,
9 });
10
11 return fetch('https://api.quantum-critical.com/data').then(r => r.json());
12}cacheTag pozwala oznaczać cache tagami, które później mogą być użyte do selektywnej rewalidacji.1import { cacheTag, cacheLife } from 'next/cache';
2
3async function getProduct(id: string) {
4 'use cache';
5 cacheTag(`product-${id}`);
6 cacheLife('hours');
7
8 return fetch(`https://api.quantum-store.com/products/${id}`).then(r => r.json());
9}
10
11async function getCategory(slug: string) {
12 'use cache';
13 cacheTag('categories', `category-${slug}`);
14 cacheLife('days');
15
16 return fetch(`https://api.quantum-store.com/categories/${slug}`).then(r => r.json());
17}1// app/actions/revalidate.ts
2'use server';
3
4import { revalidateTag } from 'next/cache';
5
6export async function updateProduct(id: string, data: ProductData) {
7 // Aktualizacja produktu w bazie
8 await db.products.update(id, data);
9
10 // Rewalidacja cache dla tego produktu
11 revalidateTag(`product-${id}`);
12}
13
14export async function refreshAllCategories() {
15 // Rewalidacja wszystkich kategorii naraz
16 revalidateTag('categories');
17}1// app/lib/dashboard-data.ts
2import { cacheTag, cacheLife } from 'next/cache';
3
4// Dane produktów - cache na godziny, tagowane
5export async function getDashboardProducts() {
6 'use cache';
7 cacheTag('dashboard', 'products');
8 cacheLife('hours');
9
10 const response = await fetch('https://api.quantum-store.com/dashboard/products');
11 return response.json();
12}
13
14// Statystyki sprzedaży - cache na minuty (częste aktualizacje)
15export async function getSalesStats() {
16 'use cache';
17 cacheTag('dashboard', 'sales');
18 cacheLife('minutes');
19
20 const response = await fetch('https://api.quantum-store.com/dashboard/sales');
21 return response.json();
22}
23
24// Dane użytkowników - cache na dni
25export async function getUserStats() {
26 'use cache';
27 cacheTag('dashboard', 'users');
28 cacheLife('days');
29
30 const response = await fetch('https://api.quantum-store.com/dashboard/users');
31 return response.json();
32}1// app/actions/dashboard-actions.ts
2'use server';
3
4import { revalidateTag } from 'next/cache';
5
6export async function refreshDashboard() {
7 // Rewalidacja całego dashboardu
8 revalidateTag('dashboard');
9}
10
11export async function refreshSalesOnly() {
12 // Rewalidacja tylko sprzedaży
13 revalidateTag('sales');
14}1// app/dashboard/page.tsx
2import { getDashboardProducts, getSalesStats, getUserStats } from '@/lib/dashboard-data';
3import { refreshDashboard, refreshSalesOnly } from '@/actions/dashboard-actions';
4
5export default async function DashboardPage() {
6 const [products, sales, users] = await Promise.all([
7 getDashboardProducts(),
8 getSalesStats(),
9 getUserStats(),
10 ]);
11
12 return (
13 <div className="quantum-dashboard">
14 <header className="flex justify-between items-center">
15 <h1>Dashboard Quantum Store</h1>
16 <div className="flex gap-2">
17 <form action={refreshSalesOnly}>
18 <button type="submit">Odśwież sprzedaż</button>
19 </form>
20 <form action={refreshDashboard}>
21 <button type="submit">Odśwież wszystko</button>
22 </form>
23 </div>
24 </header>
25
26 <div className="grid grid-cols-3 gap-6">
27 <ProductsWidget data={products} />
28 <SalesWidget data={sales} />
29 <UsersWidget data={users} />
30 </div>
31 </div>
32 );
33}| Cecha | use cache | unstable_cache | |-------|-----------|----------------| | Syntax | Dyrektywa | Funkcja wrapper | | Konfiguracja czasu | cacheLife() | Opcje revalidate | | Tagowanie | cacheTag() | tags w opcjach | | Scope | Funkcja lub plik | Tylko funkcja | | Status | Stabilne (Next.js 15) | Deprecated |
Przed (stary sposób):
1import { unstable_cache } from 'next/cache';
2
3const getCachedProducts = unstable_cache(
4 async () => {
5 return fetch('https://api.com/products').then(r => r.json());
6 },
7 ['products'],
8 { revalidate: 3600, tags: ['products'] }
9);Po (nowy sposób):
1import { cacheTag, cacheLife } from 'next/cache';
2
3async function getProducts() {
4 'use cache';
5 cacheTag('products');
6 cacheLife('hours');
7
8 return fetch('https://api.com/products').then(r => r.json());
9}Dyrektywa
use cache w Next.js 15 wprowadza:cacheLife z profilami lub własną konfiguracjącacheTag do precyzyjnego odświeżaniaW Metropolii Quantum 2150, gdzie dane przepływają z prędkością światła, odpowiednie cachowanie to różnica między aplikacją błyskawiczną a taką, która ledwo zipie. Opanuj
use cache i twoje aplikacje Next.js będą działać na najwyższych obrotach!