Avoid redundant API calls in NextJS app router

Optimizing API calls and reducing redundant requests with React.cache in NextJS. Avoid fetching same data from the database multiple times.

Published on
2 read
Avoid redundant API calls in NextJS app router

API calls are expensive in terms of user experience but they cannot be avoided for dynamic applications. However, attempts should be made to reduce redundant requests hitting the server. NextJS has leaped as a framework with a lot of good practices for developers to make the development process easy.  They have patched the fetch function to enable caching by default.  However, if you are using the NextJS app router, then you might have come across this function - generateMetadata. It allows you to generate metadata for your routes, such as title and description, which can be helpful for SEO.

If you are using a database to get meta information and also to render your app, then you might be fetching these requests twice. Let's see an example:

export async function generateMetadata() {
    const post = await queryPost(1); //<============== call 1
    return {
        title: post.title,
        // ...
    }
}

export default async function BlogPostPage() {
    const post = await queryPost(1); //<============== call 2
    return <Post data={post} />
}

You will notice that we are making two calls to the same API.  To avoid this, we can use React.cache in the following way:

const queryPostHandler = React.cache(async (id) => queryPost(id));

export async function generateMetadata() {
    const post = await queryPostHandler(1); //<============== call 1
    return {
        title: post.title,
        // ...
    }
}

export default async function BlogPostPage() {
    const post = await queryPostHandler(1); //<============== call 2
    return <Post data={post} />
}

By encapsulating the function with React.cache(), the first encounter with the database read operation triggers a "cache miss," prompting data retrieval from the database. Yet, subsequent requests for the identical read operation yield a "cache hit," delivering the data stored in the cache.

Author
Abhishek Saha
Abhishek Saha

Passionate about exploring the frontiers of technology. I am the creator and maintainer of Letterpad which is an open source project and also a platform.

Discussion (0)

Loading Related...
Subscribe