# React Memoization and cache(): My Personal Reference Guide
React automatically memoizes fetch() GET requests during a render. This means that if the same fetch() request is made multiple times with the same arguments within the same render, React performs the network request only once and reuses the result for subsequent calls.
React automatically memoizes fetch() GET requests during a render. This means that if the same fetch() request is made multiple times with the same arguments within the same render, React performs the network request only once and reuses the result for subsequent calls.
Memoization is a React default behavior where fetch requests are cached by default, such that subsequent renders within the same page do not duplicate the fetch operations. It only applies to the GET method. If you want the same behavior for other database GET requests without using "fetch", you use the cache() function.
How it works under the hood
-
When you make your request, React first checks its internal store.
-
If it finds no cache, it provides a temporary store where it saves your request.
-
If you make a subsequent request within the same page, it checks if it is exactly the same fetch together with its arguments. If it matches, it gives you the cached result without refetching.
-
Once React completes the render and commits the changes to the DOM, the cache is completely cleared.
-
If the page re-renders or the user navigates, the cache is created from scratch.
Key problems solved
-
Prop drilling: No need to pass data down multiple levels just to share it.
-
Duplicate network requests: Avoids hitting the network multiple times across different components.
Important things to note
-
Server vs Client: React
cache()lives only on the server, while request memoization lives on both the server and the client. -
Note: Use fetch() for HTTP requests and let React automatically memoize GET requests. Use cache() when you want the same request-scoped memoization for your own functions, such as Prisma queries, file reads, or expensive computations.
-
HTTP Methods: React only caches GET requests. POST, PATCH, and DELETE will bypass the cache automatically because they represent mutations.
Comments (0)
No comments yet. Be the first to share your thoughts.