Combining data fetching strategies
Next.js has two forms of pre-rendering: Static Generation and Server-side Rendering. The difference is in when it generates the HTML for a page.
- Static Generation is the pre-rendering method that generates the HTML at build time. The pre-rendered HTML is then reused on each request.
- Server-side Rendering is the pre-rendering method that generates the HTML on each request.
Sometimes we need to have data in our page that is not static and we tend to move away from getStaticProps
to getServerSideProps
.
A real-world example
We have an e-commerce product page that is statically generated, but we need to disable the "Add to cart" button if we have no stock. We can combine our data fetching strategies to get the best of both worlds. We will still generate our product page statically but we will fetch our stock periodically to update our UI.
This page is statically generated so you can see the example below. We are using SWR to fetch the stock status every 5 seconds and disable the "Add to cart" button if we have no stock. The stock is a random number so you can see the button getting disabled and enabled several times.