[React] history를 이용한 브라우저 뒤로가기 감지

haxwon·2023년 4월 12일
0

Library

목록 보기
4/5
post-thumbnail

npm history

💡 npm install history

history

const history = createBrowserHistory()
...

useEffect(() => {
    return history.listen((location) => {
      if (history.action === "PUSH") {
        setLocationKeys([location.key]);
      }
      if (history.action === "POP") {
        if (locationKeys[1] === location.key) {
          setLocationKeys(([_, ...keys]) => keys);
        } else {
          setLocationKeys((keys) => [location.key, ...keys]);
          history.push("/detail");
        }
      }
    });
  }, [locationKeys, history]);
profile
그냥 하는 프론트엔드 개발자

0개의 댓글