본문 바로가기
TIL

[TIL] 2023.07.01 Next.js_router.push와 router.replace의 차이점

by heereal 2023. 7. 1.

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')` 후, 리다이렉트 페이지에서 뒤로 가기 버튼을 누르면 로그인의 전 페이지로 돌아가게 된다.

참고 문서

 

Functions: useRouter | Next.js

Using App Router Features available in /app

nextjs.org

 

Next.js Router 정리

Next.js 라우터 사용시 정확한 정의를 모르고 사용하는 부분이 많은 것 같아 자주 사용하는 메서드를 정리해보았습니다.

velog.io

 

[Next.js] router.push와 router.replace의 차이

로그인을 완료 하고 나서 뒤로가기 버튼을 누르면 어떤 페이지로 이동해야 할까? 로그인 상태는 유지하고 로그인 화면에 들어오기 전 화면으로 이동하는 것이 매끄러울 것이다. 라우팅을 할 때

e-juhee.tistory.com

 

 

 

댓글