Deduplication
Learn how to use deduplication to optimize your application.
Deduplication prevents redundant operations for identical requests by reusing cached results. This technique enhances performance and reduces unnecessary processing.
Using React.cache
React.cache
is an in-memory caching mechanism designed to deduplicate function calls within the same request. When invoked with identical parameters, it returns cached results instead of performing the same operation again. This can significantly improve efficiency in your React applications.
Example: Deduplicating auth
from Auth.js
A common use case for React.cache
is deduplicating calls to authentication methods like the auth
function from Auth.js
. Here's how you can achieve this:
import { cache } from 'react';
// Deduplicates the 'auth' function calls within a session
export const dedupedAuth = cache(auth);
Calling dedupedAuth multiple times within a single request ensures it only runs once, with subsequent calls using the cached result. This approach enhances efficiency and resource utilization, particularly beneficial in scenarios with parallel routes.