
Title: React Router v6 문제 해결: history.listen 메서드 대체
React Router v6에서 누락된 history.listen 메서드
React Router v5를 사용하셨다면, history 객체에서 제공하는 history.listen 메서드에 익숙할 수 있습니다. 이 편리한 메서드를 사용하면 경로 이름이 변경될 때 특정 동작을 수행하거나 다시 렌더링을 트리거할 수 있었습니다. 그러나 React Router v6에서는 이 메서드가 제거되어 유사한 기능을 얻을 수 있는 대체 방법이 있는지 궁금해하는 개발자가 있습니다.
useLocation을 효과적으로 사용하기, 하지만 주의해야 할 점
React Router v6에서 주요 옵션 중 하나는 현재 위치가 변경될 때마다 부작용을 수행하기 위해 useLocation 훅을 사용하는 것입니다. 이는 적절한 대안처럼 보일 수 있지만, useLocation은 경로 이름이 변경될 때뿐 아니라 상태가 변경될 때도 렌더링 됨을 꼭 기억해야 합니다.
경로 이름이 변경될 때에만 다시 렌더링을 트리거해야 한다면, usePathname과 같은 커스텀 훅을 사용할 수 있습니다:
import { BrowserHistory } from "history";
import React, { useContext } from "react";
import { UNSAFE_NavigationContext } from "react-router-dom";
export default function usePathname(): string {
let [state, setState] = React.useState(window.location.pathname);
const navigation = useContext(UNSAFE_NavigationContext).navigator as BrowserHistory;
React.useLayoutEffect(() => {
if (navigation) {
navigation.listen((locationListener) => setState(locationListener.location.pathname));
}
}, [navigation]);
return state;
}
이 커스텀 훅은 BrowserHistory 객체에서 사용 가능한 강력한 listen 메서드를 활용하여 위치 변경 사항을 추적하고 상태를 업데이트합니다.
기타 해결 방법과 옵션
위의 접근 방식이 필요한 요구사항을 충족시키지 못한다면, 위치 변경을 처리하기 위해 커스텀 useListen 훅을 생성하는 것도 고려해볼 수 있습니다:
import { useState } from "react";
import { useLocation } from "react-router";
interface HistoryProps {
index: number;
isHistoricRoute: boolean;
key: string;
previousKey: string | null;
}
export const useHistory = (): HistoryProps => {
const { key } = useLocation();
const [history, setHistory] = useState([]);
const contemporaneousHistory = history.includes(key) ? history : [...history, key];
const index = contemporaneousHistory.indexOf(key);
const isHistoricRoute = index + 1 < contemporaneousHistory.length;
const state = { index, isHistoricRoute, key, previousKey: null };
if (history !== contemporaneousHistory) setHistory(contemporaneousHistory);
return state;
}
프로젝트의 특정 요구사항을 기반으로 이러한 임시 방안을 테스트하고 수정해야 합니다. 각 솔루션은 장단점이 있으므로 자신의 요구사항에 가장 적합한 방법을 선택하세요.
결론
React Router v6은 API에서 history.listen 메서드를 제거했지만, 유사한 기능을 구현할 수 있는 대체 방법이 있습니다. usePathname 또는 useListen과 같은 커스텀 훅을 사용하여 경로 이름의 변경 사항을 추적하고 다시 렌더링하거나 특정 동작을 수행할 수 있습니다.
이러한 임시 해결 방법을 구현하기 전에, 프로젝트의 특정 요구사항과 완벽히 일치하는지를 철저히 테스트하고 확인하는 것이 중요합니다. React Router API의 변경 사항을 이해하는 것은 React 애플리케이션에서 견고한 라우팅 시스템을 유지하고 문제를 해결하기 위해 필수적입니다.