02 / 08

Discuss Request Memoization caching mechanism?

Next.js extends the fetch API to automatically memoize requests that have the same URL and options.

How Request Memoization Works
  1. 1

    While rendering a route, the first time a particular request is called, its result will not be in memory and it'll be a cache MISS.

  2. 2

    Therefore, the function will be executed, and the data will be fetched from the external source, and the result will be stored in memory.

  3. 3

    Subsequent function calls of the request in the same render pass will be a cache HIT, and the data will be returned from memory without executing the function.

  4. 4

    Once the route has been rendered and the rendering pass is complete, memory is 'reset' and all request memoization entries are cleared.

Good to know:
  1. 1

    Request memoization is a React feature, not a Next.js feature. It's included here to show how it interacts with the other caching mechanisms.

  2. 2

    Memoization only applies to the GET method in fetch requests.

  3. 3

    Memoization only applies to the React Component tree, this means:

  4. 4

    It applies to fetch requests in generateMetadata, generateStaticParams, Layouts, Pages, and other Server Components.

  5. 5

    It doesn't apply to fetch requests in Route Handlers as they are not a part of the React component tree.

  6. 6

    For cases where fetch is not suitable (e.g. some database clients, CMS clients, or GraphQL clients), you can use the React cache function to memoize functions.

  7. 7

    Since the memoization is not shared across server requests and only applies during rendering, there is no need to revalidate it.