Why is App Router in Next.js the Future, but Pages Router Still Important?#
Next.js, as a powerful React framework, provides developers with two routing systems: App Router and Pages Router. These two routing systems have their own characteristics and are suitable for different scenarios. This article will delve into the differences, advantages, disadvantages, and use cases of these two routing systems to help you make the best choice.
App Router: The Next Generation of Routing Revolution#
App Router is a new routing system introduced in Next.js 13. It uses the app
directory to organize routes and brings many exciting new features.
Advantages:#
-
Support for React Server Components: This is a game-changer that allows rendering complex components on the server-side, greatly improving performance.
-
Flexible Layout System: With nested layouts, you can easily create complex page structures.
-
Built-in Loading UI and Error Handling: Provides a better user experience without the need for additional configuration.
-
Performance Optimization: Thanks to server components and other optimizations, App Router usually provides better performance.
-
Parallel Routing: Allows rendering multiple pages simultaneously within the same layout.
Disadvantages:#
-
Steep Learning Curve: It may take some time for those accustomed to traditional React development to adapt.
-
Compatibility with Third-Party Libraries: Some older libraries may not be compatible with the new server component mode.
-
Still Evolving: As a newer technology, there may be some unknown issues or changes.
Pages Router: A Classic and Reliable Choice#
Pages Router is the traditional routing system in Next.js, which uses the pages
directory to organize routes. It is still the preferred choice for many projects, especially for older versions of Next.js.
Advantages:#
-
Easy to Get Started: It has a relatively gentle learning curve, making it suitable for beginners.
-
Intuitive File System Routing: The routing structure corresponds directly to the file structure, making it easy to understand and manage.
-
Abundant Community Resources: Due to its long-time usage, there are plenty of tutorials, examples, and third-party library support.
-
High Stability: With years of usage and optimization, it has fewer bugs and performs reliably.
Disadvantages:#
-
Lack of Support for React Server Components: It cannot leverage the performance improvements brought by this new feature.
-
Relatively Simple Layout System: Implementing complex layouts may require more code and configuration.
-
Fixed Data Fetching Methods: It mainly relies on
getServerSideProps
andgetStaticProps
, which have lower flexibility.
Practical Comparison: Implementing a Blog Page#
Let's compare the implementation of these two routing systems using a simple blog page example:
Pages Router Implementation#
// pages/posts/[id].js
import { useRouter } from 'next/router';
export default function Post({ post }) {
const router = useRouter();
if (router.isFallback) {
return <div>Loading...</div>;
}
return (
<div>
<h1>{post.title}</h1>
<p>{post.content}</p>
</div>
);
}
export async function getStaticProps({ params }) {
const res = await fetch(`https://api.example.com/posts/${params.id}`);
const post = await res.json();
return { props: { post } };
}
export async function getStaticPaths() {
const res = await fetch('https://api.example.com/posts');
const posts = await res.json();
const paths = posts.map(post => ({
params: { id: post.id.toString() },
}));
return { paths, fallback: true };
}
In this example, we use getStaticProps
and getStaticPaths
to implement static generation. This is a typical usage of Pages Router, suitable for blog articles with infrequent content changes.
App Router Implementation#
// app/posts/[id]/page.js
import { notFound } from 'next/navigation';
async function getPost(id) {
const res = await fetch(`https://api.example.com/posts/${id}`);
if (!res.ok) return undefined;
return res.json();
}
export default async function Post({ params }) {
const post = await getPost(params.id);
if (!post) {
notFound();
}
return (
<div>
<h1>{post.title}</h1>
<p>{post.content}</p>
</div>
);
}
The implementation of App Router is more concise. Here, we directly perform asynchronous data fetching within the component, thanks to the support of React server components. Additionally, we use the notFound
function to handle the case when the article does not exist, which is one of the built-in error handling mechanisms provided by App Router.
How to Choose?#
There is no absolute right or wrong choice between App Router and Pages Router. Here are some suggestions:
-
Project Scale and Complexity: For large and complex projects, the flexibility and performance advantages of App Router may be more appealing.
-
Team Familiarity: If the team is relatively unfamiliar with Next.js, starting with Pages Router may be easier.
-
Performance Requirements: If the project has high performance requirements, App Router with server components may be a better choice.
-
Project Timeline: For projects that require rapid development, Pages Router may be more suitable due to its lower learning curve.
-
Future Outlook: Considering the direction of Next.js development, mastering App Router may have advantages in the long run.
Personal Experience Sharing#
As a developer who recently started using Next.js, I was initially confused about App Router as well. However, when I started dealing with complex layouts and scenarios that required performance optimization, the advantages of App Router became apparent.
For example, in a data-intensive application that requires frequent updates, the server components in App Router allowed me to handle most of the data logic on the server-side, significantly reducing the amount of JavaScript transferred to the client and improving the overall performance of the application.
However, for some simple projects or time-sensitive situations, I still choose Pages Router. It is straightforward and allows me to quickly prototype and deploy.
Conclusion#
Both App Router and Pages Router have their own strengths, and the choice between them depends on your specific needs and scenarios.
My advice is: don't be afraid to try new things. Even if you are currently using Pages Router, it is worth spending some time to learn about App Router.
After all, technology is constantly advancing, and staying updated is essential to avoid being left behind.
Remember, technology is just a tool. What truly matters is solving problems and creating value. Choose the tool that best suits you to maximize your productivity.
Closing Remarks#
Last time, I wrote a tool for batch cleaning unused repositories. If you're interested, check it out 😊
Introduction Article: https://mp.weixin.qq.com/s/t7lgc6b7xJiNhfm5vWo5-A
GitHub Repository: https://github.com/yaolifeng0629/del-repos
If you find this tool helpful, please don't forget to give my GitHub repository a Star! Your support is my motivation to keep moving forward!
Thank you for reading, see you next time!