2022년

Redirect, useHistory 무엇을 쓸까?

박상윤 2021. 12. 13. 13:38

코드 상황

로그인을 하면 useSWR의 fetcher를  통해 전달받은 데이터가 존재하는 경우, history.push를 이용해 /workspace/channel 페이지로 전환시켜주는 상황

 

아래와 같은 경고 발생

 

StackOverFlow 검색

https://stackoverflow.com/questions/64306989/cannot-update-during-an-existing-state-transition-such-as-within-render-ren

 

Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props a

I'm using react and react hooks for front-end and I'm getting this error: index.js:1 Warning: Cannot update during an existing state transition (such as within `render`). Render methods should ...

stackoverflow.com

 

채택된 답변

useHistory 대신에 Redirect를 사용해라!

useHistory를 사용하면 구성요소를 렌더링하는 도중에 history.push가 발생하므로, 오류가 발생한다.

Redirect 구성요소를 렌더링하면 구성요소가 렌더링을 완료한 후 리디렉션이 발생하므로, Ract Router에 의해 수행된 업데이트가 렌더 중간에 발생하지 않습니다.

 

추가 주의사항

React Hook보다 먼저 return을 호출하면 안된다!