[DEV_ERROR] react-router VS react-router-dom

EUNCHAE KIM·2023년 1월 26일
0

갑자기 왜 아무것도 안뜨지?

어제 todo앱 react-query 로직을 변경한 후 코드가 오류없이 잘 작동되는 것을 분명히 확인했었다. 그러고 나서 오늘도 개발을 이어갔다.

페이지를 벗어나기 전에 prompt를 띄어주고 싶어서 이것저것 자료를 찾아보다가 react-router를 add 하기도하고 react-router-dom 버전을 6에서 5로 낮춰보기도 했다. 그런데 앱을 실행해보니 갑자기 흰 화면만 뜨면서 콘솔창은 이런 오류들을 보여줬다.

usenavigate() may be used only in the context of a <router> component

크게 로직을 변경한 부분이 없는데 화면에 아무것도 안떠서 당황했다.
참고로 Prompt 컴포넌트는 react-router v6에서 사라졌기 때문에 usePropmt,useBlocker를 직접 구현해야한다고 한다;; (왜 없어진걸까..?)


허무한 원인

역시나 코드는 거짓말하지 않는다..ㅎㅎ 이것저것 시도해보며 react-router를 add하는 과정에서 기존의 import { useNavigate } from "react-router-dom"; 이러한 구문을 포함하고 있는 모든 페이지의 import 문이 import { useNavigate } from "react-router"; 이렇게 바뀌어있었다. 소스트리에도 코드 변경 표시가 안돼있어서 한참을 헤맸다...ㅎㅎ


react-router VS react-router-dom

내가 이 두 가지의 차이점만 어느정도 알았으면 바로 짐작할 수 있는 오류였다. 이래서 기본기가 항상 중요한가보다 (반성,,)

react-router 는 세 가지 메인 패키지와 관련이 돼있다.

1) react-router : Contains the core functionality of React Router, including route-matching algorithms and hooks.
2) react-router-dom : Includes everything in react-router and adds a few DOM-specific APIs.
3) react-router-native : Includes everything in react-router and adds a few React Native-specific APIs.

react-router-dom 패키지는 react-router 패키지에 의존하며, react-router 모듈에 'BrowserRouter', 'Link' 와 같이 dom이 바인딩 되어 있는 모듈이다.

언제 어떤걸 사용해야 할까?

  • 웹 작업을 할때 -> react-router-dom
    웹 어플리케이션 라우팅에 필수적인 모든 공용 components와 features들을 포함
    또한 react-router-dom 패키지는 react-router 패키지에 의존하기 때문에 react-router를 다시 설치하거나 import 할 필요가 없다.

  • React Native 환경의 모바일 어플리케이션을 개발 할때 -> react-router-native

참고

https://www.syncfusion.com/blogs/post/react-router-vs-react-router-dom.aspx
https://www.delftstack.com/howto/react/react-router-vs-react-router-dom/

profile
Try Everything

0개의 댓글