Caching Documentation
Introduction
Caching is a technique used to store the result of expensive operations so that future requests can be served faster. It is commonly used in web applications to reduce latency, minimize server load, and improve overall performance.
What is use cache
The use cache directive allows developers to cache the return value of asynchronous functions and components. When applied, the function or component does not re-execute if the same inputs are provided. Instead, the cached result is returned.
Usage
1. Data-Level Caching
Data-level caching is used for functions that fetch or compute data.
async function getProducts() {
"use cache";
// fetch products
}
async function getUser(id) {
"use cache";
// fetch user data
}
This approach is useful when the same data is requested multiple times, as it avoids repeated API or database calls.
2. UI-Level Caching
UI-level caching is applied to entire components or pages.
export default async function BlogPage() {
"use cache";
// render content
}
This is beneficial for pages that do not change frequently or depend on stable data.
How Caching Works
Caching is based on a cache key that is automatically generated. The key includes:
Function arguments
Variables captured from the surrounding scopeIf the same inputs are provided, the cached result is returned. If the inputs change, a new cache entry is created.
Caching Overview
Key Characteristics
- Caching is input-dependent
- Different inputs produce different cached results
- Supports dynamic and parameterized data
- Works with both functions and components
Constraints
- Only serializable data can be cached
- Non-deterministic values (e.g., random numbers, timestamps) should be avoided
- Inputs must remain stable for consistent caching behavior
Benefits
- Reduces repeated computations
- Improves response time
- Decreases API and database load
- Enhances scalability of applications
Best Practices
- Use caching for frequently requested data
- Avoid caching highly dynamic or real-time data
- Ensure proper data structure and serialization
- Monitor cache usage and invalidation strategies if applicable
Conclusion
Caching is an essential optimization technique in modern application development. The use cache directive provides a simple and effective way to implement caching at both data and UI levels. When used correctly, it significantly improves performance and efficiency.
Top comments (0)