Question:
Will getServerSideProps be populated when cached value from an API call?

Solution

Let's assume, in Next.js, we will get getServerSideProps for fetchin' data on the server side. Until the entire data fetching process is completed, the initial client-side render will be on hold. When the getServerSideProps function returns a cached value, the first render will quickly show content before hydration.


In the example provided:

export async function getServerSideProps() {

    // Retrieve data from Cache

    const cachedData = getCachedData('config');

    if (cachedData) {

        return { props: { data: cachedData } };

    }


    // Cache is empty, initiate re-fetch and caching process

    const response = await fetchAndCache(`https://.../data`);

    const fetchedData = await response.json();


    return { props: { data: fetchedData } };

}


export default function Page({ data }) {

    // Render data...

}


The first render will use the cached value returned by getCachedData('config'). If the cache is empty, the data will be fetched via an API call before being cached.


Notably, Next.js's synchronous server-side rendering (SSR) guarantees that the first render makes use of cached data when it is available, allowing for a speedy initial load. The data that has been cached will also be useful for subsequent visits during the cache duration.


Suggested blogs:

>How to conditionally render different arrays in React?

>Fix react useState and array.map not work issue

>Making infinite scrolling using react-query

>How does React State with JSON arrays affect performance?

>setlist{nosep} not work in the acronym package

>Fix ScrollIntoView not working issue

>Testing react component with jest

>How you can Show or hide elements in React?

>Testing react components using Hooks and Mocks

>Tips for using React Redux Hooks to show or hide React components


Nisha Patel

Nisha Patel

Submit
0 Answers