useRouter
import { useRouter } from 'next/navigation';
Next.js 13부터는 `useRouter`를 'next/router'가 아닌 'next/navigation'에서 import 해서 사용해야 한다!
만약 `useRouter`를 'next/router'에서 import하면 이미지와 같은 에러가 발생한다.
잠시 router 관련 Next.js 13에서 달라진 점을 살펴보자.
Migrating from the pages directory:
- The new useRouter hook should be imported from `next/navigation` and not `next/router`
- The pathname string has been removed and is replaced by usePathname()
- The query object has been removed and is replaced by useSearchParams()
- router.events is not currently supported.
router.push
router.push(href: string)
- Perform a client-side navigation to the provided route. Adds a new entry into the browser’s history stack.
- `router.push`는 라우터 히스토리 스택에 새로운 url을 쌓는다.
- 따라서 이전의 라우팅 히스토리를 모두 유지하고 싶을 때 사용한다.
- 홈 > 로그인 > 리다이렉트 페이지 > [뒤로가기] > 로그인
- 로그인 페이지에서 `router.push('/redirect')` 후, 리다이렉트 페이지에서 뒤로 가기 버튼을 누르면 로그인 페이지로 돌아간다.
router.place
router.replace(href: string)
- Perform a client-side navigation to the provided route without adding a new entry into the browser’s history stack.
- `router.replace`는 기존에 있던 현재 페이지 route를 새로운 url로 대체한다.
- 현재 라우팅 히스토리를 다른 url로 변경하고 싶을 때 사용한다. (예: 로그인 후 마이페이지 이동했을 때 뒤로 가기로 다시 로그인 페이지로 가지 않기 위해 로그인 url을 history에서 제거)
- 홈 > 로그인 > 리다이렉트 페이지 > [뒤로가기] > 홈
- 로그인 페이지에서 `router.replace('/redirect')` 후, 리다이렉트 페이지에서 뒤로 가기 버튼을 누르면 로그인의 전 페이지로 돌아가게 된다.
참고 문서