[Next.js 13] page에서 app으로 라우터 변경했을 때 발생하는 문제 모음

XCC629·2023년 3월 3일
1

개인프로젝트

목록 보기
2/2

1. use client

경고문

You're importing a component that needs useRef. It only works in a Client Component but none of its parents are marked with "use client", so they're Server Components by default.

답변

In the app directory, by default, Next.js uses Server Components, where the JSX gets compiled to "pure HTML" and sent to the browser. Like any traditional Backend with a templating engine, such as Express with EJS, and Laravel with Blade. This is for better performance, as you can read on the doc:

app 디렉토리에서는 기본적으로, Next.js는 jsx가 "퓨어 HTML"를 컴파일하고 브라우저에게 전송하는 Server Components를 사용한다. (중략) 더나은 퍼포먼스를 위해서!

Server Components allow developers to better leverage server infrastructure. For example, large dependencies that previously would impact the JavaScript bundle size on the client can instead remain entirely on the server, leading to improved performance.

Server Componets는 개발에게 더 나은 레버레지 서버 인프라를 사용하게 한다. 예를 들어,이전에 클라이언트의 자바스크립트 번들 크기에 영향을 미쳤던 큰 종속성은 대신 서버에 전체적으로 남아 성능을 향상시킬 수 있다.

And a Server Component shouldn't contain front-end-specific code, for example, hooks such as useState or useEffect. If you need that, your component or one of its parents should have "use client" at the top, to make it a Client Component:

server Component에서는 useState, useEffect 같은 프론트엔드-특별(?) 코드를 포함할 수 없다. 그래도 Client Component로 사용하고 싶으면, 컴포넌트 혹은 그것의 부모의 가장 상위에 "use Client"라는 코드를 넣어라.

"use client"; // this is a client component 👈🏽

import { useState } from "react";

export default function FileUploader() {
  const [files, setFiles] = useState([]);

  return (
    <div>
      Hello World
    </div>
  );
}

참고: https://stackoverflow.com/questions/74965849/youre-importing-a-component-that-needs-usestate-it-only-works-in-a-client-comp

정리

  1. app 디렉토리는 server component와 client component를 분리해서 만들었다.
  2. router의 기본이 되는 page.tsx는 server component다.
  3. 그래서 useState, useEffect를 기본적으로는 사용할 수 없다.
  4. 꼭 사용하고 싶다면, 걔 혹은 걔 부모에게 코드 가장 상위에 'use Client'라는 코드를 남겨라.

2. API Routes가 아닌 Route Handlers

App dir을 하게 되면, 기존에 쓰던 API routes 방식이 아닌 Route handlers를 사용해야 정상 작동 합니다.

Good to know: Route Handlers are only available inside the app directory. They are the equivalent of API Routes inside the pages directory meaning you do not need to use API Routes and Route Handlers together.

Route Handlers은 app dir방식에서만 사용가능합니다. 이 방식은 Page dir에서의 API Routes와 동일합니다. 그러므로 두 가지 방식을 함께 사용할 필요는 없습니다.

Route Handlers 사용법

공식문서: https://beta.nextjs.org/docs/routing/route-handlers#robotstxt-rssxml-and-sitemapxml


3.Dynamic segments

https://beta.nextjs.org/docs/routing/defining-routes#dynamic-segments

A Dynamic Segment can be created by wrapping a folder’s name in square brackets: [folderName]. For example, [id] or [slug].

다이나믹 세그먼트는 대괄호로 쌓은 이름을 가진 폴더로부터 만들어질 수 있다.

pages dir 방식> post/[id].tsx
app dir 방식 > post/[id]/page.tsx

Dynamic Segments are passed as the params prop to layout, page, route, and generateMetadata functions.

다이나믹 세그먼트는 매개 변수가 레이아웃, 페이지, 라우팅 및 메타데이터 함수 생성을 제안할 때 전달됩니다.

예시

params을 사용할 때도 기존과는 달리 아래와 같이 사용해주면 됩니다.

export default function Page({params}){
	return <div>My post</div>
}
profile
프론트엔드 개발자

0개의 댓글