skip to Main Content

I’m currently working with Next.js and using the fetch method to retrieve data:

const res = await fetch(`${process.env.url}/test`, {
  cache: 'no-store',
})

As I understand it, specifying cache: 'no-store' should force a new data fetch each time a user loads a page.

This has led me to question whether this option makes the component behave more like it’s client-side rendered. Usually, when I execute npm run build, Next.js generates static HTML files after fetching data at build time.

However, using cache: 'no-store' appears to cause data to be fetched each time the page is loaded, not at build time. Does this mean that my component is essentially behaving as if it were client-side rendered? I would appreciate any clarification on this matter.

async function fetchItems() {
  const res = await fetch(`${process.env.url}/test`, {
    cache: 'no-store',
  })

  const items: Item[] = await res.json()
  return items
}

export const ItemList = async () => {
  const items = await fetchItems()
  return (
    <ul>
      {items.map((item) => (
        <li key={item.id}>
          {item.title}
        </li>
      ))}
    </ul>
  )
}

2

Answers


  1. When you add cache: 'no-store' as an option to fetch, it means disabling Static Rendering (generating HTML files at build time, caching them, and sending them when there is a request) and using Dynamic Rendering (generating HTML files after there is a request and sending them).

    The component still fetchs data and renders on the server, so no, it’s not like making a call client side in a useEffect, in which case, the part that depends on the fetched data will not be in the initial HTML the server sends.

    Login or Signup to reply.
  2. if it was behaving as if it were client-side rendered, you would not have async component.

    async function fetchItems() {}
    

    async component works only on server. no-store makes it like getServerSideProps. by default next.js caches fetched data, if you were fetching a user from the database, you would always get the initial user.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search