Immerse

Immerse

github
email
twitter
youtube
zhihu

Next.js Routing Revolution: Why App Router Might Be the Future, But Pages Router Still Matters

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, which uses the app directory to organize routes and brings many exciting new features.

Advantages:#

  1. Support for React Server Components: This is a game-changer that allows complex components to be rendered on the server, greatly improving performance.

  2. Flexible layout system: With nested layouts, you can easily create complex page structures.

  3. Built-in loading UI and error handling: Provides a better user experience without the need for additional configuration.

  4. Performance optimization: Thanks to server components and other optimizations, App Router usually provides better performance.

  5. Parallel routing: Allows multiple pages to be rendered simultaneously in the same layout.

Disadvantages:#

  1. Steep learning curve: It may take some time for those accustomed to traditional React development to adapt.

  2. Compatibility with third-party libraries: Some older libraries may not be compatible with the new server component mode.

  3. 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:#

  1. Easy to get started: It has a relatively gentle learning curve for beginners.

  2. Intuitive file system routing: The routing structure corresponds one-to-one with the file structure, making it easy to understand and manage.

  3. Abundant community resources: Due to its long-time usage, there are plenty of tutorials, examples, and third-party library support.

  4. High stability: With years of usage and optimization, it has fewer bugs and performs stably.

Disadvantages:#

  1. Lack of support for React Server Components: Unable to leverage the performance improvements brought by this new feature.

  2. Relatively simple layout system: Implementing complex layouts may require more code and configuration.

  3. Fixed data fetching methods: Mainly relies on getServerSideProps and getStaticProps, with lower flexibility.

Practical Comparison: Implementing a Blog Page#

Let's compare the implementation of these two routing systems through 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. At the same time, we use the notFound function to handle the case where 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:

  1. Project scale and complexity: For large and complex projects, the flexibility and performance advantages of App Router may be more appealing.

  2. Team familiarity: If the team is relatively unfamiliar with Next.js, starting with Pages Router may be easier to get started.

  3. Performance requirements: If the project has high performance requirements, App Router with server components may be a better choice.

  4. Project timeline: For projects that require rapid development, Pages Router may be more suitable due to its lower learning curve.

  5. Future prospects: Considering the direction of Next.js development, mastering App Router may have advantages in the long run.

Personal Experience Sharing#

As a developer who initially 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, App Router's server components allowed me to handle most of the data logic on the server, significantly reducing the amount of JavaScript transferred to the client and improving the overall performance of the application.

However, for some simple projects or situations with tight deadlines, I still choose Pages Router. It is simple and straightforward, allowing me to quickly prototype and go live.

Conclusion#

Both App Router and Pages Router have their own merits, 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 understand App Router.

After all, technology is constantly advancing, and staying updated is the key to not being left behind.

Remember, technology is just a tool. What really 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, take a look 😊

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 move forward!

Thank you for reading, see you next time!

image

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.