While reading the Next.Js tutorial in the Routing API I learned about fetching data with these 2 libs.
The fetch object from Isomorphic-unfetch, is used within the getInitialProps async function to call an external API. Then in the Route API part, the SWR along with the { useRouter } from 'next/router; shapes the call to an internal API developed within the same Next.Js server with a lot of flexibility to query the req params.
Other than these 2 aspects, what other differences are between these 2 approaches?
isomorphic-unfetch allows you to make fetch calls on both the client and the server, which is why it's shown in examples that use getInitialProps.
Generally speaking, you fetch data on the server using getInitialProps. This will be blocking – meaning the markup will not be returned until your data has been fetched. Consider a product page for an e-commerce site. It's important that we return the product name, price, and other information from the server and not on the client-side.
SWR is similar, but a bit different. It first returns the data from cache (stale), then sends the fetch request (revalidate), and finally comes with the up-to-date data again. A real-world example of where you'd use something like SWR is on a dashboard page. You don't want to fetch all the data in getInitialProps in a blocking manner, so you render out the dashboard "shell" in a loading state, and then use SWR to fetch the data client side. You can view an example of this here.
Source - Creator of Mastering Next.js 😄
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With