React에서 라우팅을 하려면 useNavigate 혹은 Navigation 컴포넌트를 활용한다. 기존에 vanila.js에서는 window.location을 통해서 이동하였는데 그 차이가 뭘까?

만약 Pick, Partial과 같은 Utility Type에 익숙하지 않다면 아래 포스팅을 먼저 읽고오자!

[TypeScript] 유틸리티 타입 (Pick, Omit, Partial, Record 등)

history.pushstate vs window.location


결론부터 말하자면 react-router의 useNavigatehistory.pushState를 사용한다.

<aside> 💡 만약 url이 hash fragment이면 새 HTTP요청을 하지 않고 연관된 앵커로 스크롤된다.

</aside>

history.pushstate window.location.herf
HTTP 요청
페이지 새로고침
Application 상태 유지

위 특징을 보면 알 수 있듯이, 무조건 useNavigate를 사용할 필요는 없을 것 같다. 만약 이동과 동시에 새로고침이 필요하다면 window.locaiton.herf를 적절히 사용하면 되겠다.

react-router코드 살펴보기


react-router github