Too many re-renders Error!

HMJ·2024년 12월 20일
Too many re-renders. React limits the number of renders to prevent an infinite loop.
    at renderWithHooksAgain (http://localhost:3000/static/js/bundle.js:13699:55)
    at renderWithHooks (http://localhost:3000/static/js/bundle.js:13659:63)
    at updateFunctionComponent (http://localhost:3000/static/js/bundle.js:14926:17)
    at beginWork (http://localhost:3000/static/js/bundle.js:15544:16)
    at runWithFiberInDEV (http://localhost:3000/static/js/bundle.js:10885:14)
    at performUnitOfWork (http://localhost:3000/static/js/bundle.js:18129:93)
    at workLoopSync (http://localhost:3000/static/js/bundle.js:18023:38)
    at renderRootSync (http://localhost:3000/static/js/bundle.js:18007:7)
    at performWorkOnRoot (http://localhost:3000/static/js/bundle.js:17768:42)
    at performSyncWorkOnRoot (http://localhost:3000/static/js/bundle.js:18578:5)

Radio onChange로 value (0, 1) 값을 받아서, 배열(2차배열)의 첫번째 인자를 구분하고, 그 배열을 body에서 map으로 button을 생성하는 도중에 위의 에러가 뜨게 되었다.

아래의 링크를 읽어본 결과, state의 변화가 무한반복되어서 나타나는 에러로, button에서 onClick={handleButtonClick(index)} 부분이 문제였다. handleButtonClick(index)로 주면 바로 함수가 실행이 되기 때문에, 함수 안에 있던 setPayButtonMethod(index);라는 state를 값을 변경하는 로직이 계속 실행이 되어 무한 반복에 걸리게 된다.

해결은 onClick={() => handleButtonClick(index)}로 일급 함수 형태로 가지고 오면 된다. 함수를 실행이 아닌 인자로 넘겨주는 것이기 때문에, 무한 반복에 걸리지 않는다.

참고 링크

https://wnsdufdl.tistory.com/245
https://anerim.tistory.com/161

0개의 댓글