본문 바로가기
TIL

[TIL] 2023.05.07 Next.js next/navigation과 usePathname()

by heereal 2023. 5. 7.

route에 따라 코드를 다르게 작성하고 싶어서 useRouter를 이용해서 pathname을 가져오려고 했다. 그런데 서버 컴포넌트를 사용할 때는 next/navigation을 사용하라는 에러 메시지가 떴다.

 

// 수정 전
import { useRouter } from 'next/router';

// 수정 후
import { useRouter } from 'next/navigation';

그래서 useRouter를 next/navigation에서 import 해 오는 방식으로 수정했는데 또다시 클라이언트 컴포넌트에서만 useRouter를 사용할 수 있다는 에러 메시지가 발생했다. 그래서 최상단에 "use client"를 추가하여 서버 컴포넌트를 클라이언트 컴포넌트로 변경해 주었다.

 

import { useRouter } from 'next/navigation';
...
const router = useRouter();
console.log(router);

그리고 router를 콘솔에 찍어봤지만 내가 원하는 pathname은 찾을 수 없었다. 

 

공식 문서를 찾아보니 이제 useRouter는 next/navigation에서 import하여 사용해야 하며, pathname을 얻기 위해서는 useRouter()도 아닌 별도의 usePathname()을 사용해줘야 하는 거 같다.

 

'use client';
 
import { usePathname } from 'next/navigation';
 
export default function ExampleClientComponent() {
  const pathname = usePathname();
  return <>Current pathname: {pathname}</>;
}

결론적으로 Next.js 13 버전에서 pathname을 가져오려면 usePathname()이라는 hook을 사용하면 된다.

 

참고

https://stackoverflow.com/questions/74421327/nextrouter-was-not-mounted-next-js

https://nextjs.org/docs/app/api-reference/functions/use-router

https://nextjs.org/docs/app/api-reference/functions/use-pathname

 

 

댓글