Created
September 30, 2025 05:31
-
-
Save devheedoo/180e6fc8c0ab1435f5a7e8bcb2a3e9e8 to your computer and use it in GitHub Desktop.
특정한 상황에서는 idx 값이 NaN이 될 수 있음을 고려한 뒤로가기 훅
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { useNavigate } from "react-router-dom"; | |
| import { useCallback } from "react"; | |
| /** 특정한 상황에서는 idx 값이 NaN이 될 수 있음을 고려한 뒤로가기 훅 */ | |
| export function useSafeBack(defaultPath: string = "/home") { | |
| const navigate = useNavigate(); | |
| const safeBack = useCallback(() => { | |
| const idx = window.history.state?.idx; | |
| // case 1: React Router idx가 유효하고 0보다 크다 → safe하게 뒤로 | |
| if (Number.isFinite(idx) && idx > 0) { | |
| navigate(-1); | |
| return; | |
| } | |
| // case 2: idx가 NaN이지만, 브라우저 history stack이 2 이상이다 → 시도 | |
| if (!Number.isFinite(idx) && window.history.length > 1) { | |
| let didPop = false; | |
| const handler = () => { | |
| didPop = true; | |
| window.removeEventListener("popstate", handler); | |
| }; | |
| window.addEventListener("popstate", handler); | |
| navigate(-1); | |
| // 300ms 정도 기다려서 popstate가 없으면 fallback | |
| setTimeout(() => { | |
| if (!didPop) { | |
| navigate(defaultPath, { replace: true }); | |
| } | |
| }, 300); | |
| return; | |
| } | |
| // case 3: idx=0 이거나 stack이 아예 없음 → fallback으로 이동 | |
| navigate(defaultPath, { replace: true }); | |
| }, [navigate, defaultPath]); | |
| return safeBack; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment