Next.js App Router basics and benefits of introductionNext.js App Router basics and benefits of introduction

Next.js App Router basics and benefits of introduction

“App Router” was introduced in Next.js 13 and has now become standard. The concept has changed significantly from the previous Pages Router, so some people may still be hesitant to migrate. This article provides a step-by-step guide to the basics of understanding App Router.

Step 1: Understand the differences in directory structure

In the previous Pages Router, the file name in the pages directory was used as URL routing (for example, pages/about.tsx → /about).

App Router uses the app directory. URL routing is determined by the folder name, and the rule has changed to always place a file named page.tsx in that folder (e.g. app/about/page.tsx → /about). Although this may seem troublesome at first glance, it has the great advantage of allowing components and test files unrelated to routing to coexist in the same folder.

Step 2: Understand the layout concept

A powerful feature of App Router is “Layout”. Creating app/layout.tsx allows you to apply a common UI (header, footer, etc.) to all pages under that folder. What is noteworthy is that this Layout part is not re-rendered when the page transitions. This allows for smooth screen transitions while preserving the state, greatly improving application performance.

Step 3: Draw the line between server and client

This is the most important change. Components in App Router default to React Server Components (components that run on the server side). You cannot use browser APIs (such as window) or React hooks (such as useState and useEffect) inside server components.

If you need a button click event, etc., you need to explicitly convert it to a client component by writing "use client" at the top of the file. The key to success with App Router is to keep in mind that ``basically, the server performs some light rendering, and only the interactive parts are left to the client.''

Step 4: Simplify data fetching

Previously required Next.js-specific functions such as getServerSideProps and getStaticProps have been deprecated. Instead, just use the standard fetch API by await directly within your component. Next.js has internally extended fetch, and you can now control the cache intuitively just by using the optional arguments of fetch.

App Router isn’t scary if you understand it step by step. Please take the first step towards more advanced and faster web application development.