Programming

[TIL] window.location / useNavigate 차이

jay-dev 2023. 7. 14. 01:50

window.location

문서의 현재 위치에 대한 정보와 함께 location 객체를 반환하는 속성
아래 세가지 모두 다른페이지로 리다이렉션 하는 데 사용되지만 브라우저에 미치는 영향은 다름

1. window.location.href

현재 웹페이지의 속성을 저장 (새 URL로 이동했을 때 뒤로가기로 돌아올 수 있음)

assign보다 빠름

function setCurrentLocation() {
 
            // Change current location
            let newloc = "https://www.geeksforgeeks.org/";
            window.location.href = newloc;
        }


window.location.replace

현재 웹페이지의 속성을 새 URL로 덮어버림(새 URL에서 뒤로가기를 눌렀을 때 현재 페이지로 돌아올 수 없음)

현재 페이지를 세션 기록에서 삭제

function replaceLocation() {
 
            // Replace the current location
            // with new location
            let newloc = "https://www.geeksforgeeks.org/";
            window.location.replace(newloc);
        }

window.location.assign

뒤로가기 가능

href보다 안전함

function assignLocation() {
 
            // Go to another webpage (geeksforgeeks)
            let newloc = "https://www.geeksforgeeks.org/";
            window.location.assign(newloc);
        }

 

useNavigate

useNavigate는 history 모듈에 의존

아래는 history 구조

...
globalhistory = window.history
...

...
function push(to: To, state?: any) {
  let nextAction = Action.Push;
  let nextLocation = getNextLocation(to, state);
  function retry() {
    push(to, state);
  }

  if (allowTx(nextAction, nextLocation, retry)) {
    let [historyState, url] = getHistoryStateAndUrl(nextLocation, index + 1);

    // TODO: Support forced reloading
    // try...catch because iOS limits us to 100 pushState calls :/
    try {
      globalHistory.pushState(historyState, '', url);
    } catch (error) {
      // They are going to lose state here, but there is no real
      // way to warn them about it since the page will refresh...
      window.location.assign(url);
    }

    applyTx(nextAction);
  }
}

window.history를 이용한 리다이렉트

 

useNavigate는 뒤로가기시 새로운 HTTP요청 x

window.location은 새로운 HTTP 요청

'Programming' 카테고리의 다른 글

[github] 협업을 위한 branch 생성시 git pull & pull request  (0) 2023.07.23
[WIL] week5 회고  (0) 2023.07.17
[TIL] React Portal을 사용해 Modal 만들기  (0) 2023.07.12
[TIL] React Query  (0) 2023.07.11
[TIL] React Hooks  (1) 2023.07.09