Member-only story
Routing and Data Fetching in Next.js
A guide to using file-based routers and dynamic routing
In this article, we will cover:
- How to render specific components on different routes.
- The difference between static and server-side generation.
- Fetching data with
getStaticProps
. - Getting data and dynamically generating routes with
getStaticPaths
. - Getting API data on the server side via
getServerSideProps
.
Introduction
One day, a client hires you to build a website for them in React. These are their requirements:
- It should not be a traditional single-page web app. Instead, the website should have separate pages that would be rendered on their respective routes.
- Since the website is supposed to be static, performance has to be the top priority.
“No problem,” you tell them. “I have already used React Routers before. This work will be effortless.” However, since it is a static website, you want the website’s performance to skyrocket. “How do I build a performant website?” you ask yourself.
After some research, you find out that there is a framework called Next.js.
What is Next.js and when should you use it?
The birth of Next.js has caused many developers to jump ship from plain React to Next.js. Surely, there must be something that sets it apart, right?
To that, my answer is a solid yes. According to this Stack Overflow post, this library utilizes an easy-to-use routing system that allows the programmer to display specific components on specific routes. Moreover, it also allows for server-side rendering. This method allows loading time to be spread over time, which makes performance better. Furthermore, according to Lee Robinson (a contributor to Next.js), the technology gives you the flexibility to use either server-side or client-side rendering on a per-page basis.
You might be wondering, “So why not use plain React with React Routers? There is no need to learn yet another framework.” To that, my response is that in plain React, if your app’s size becomes…