Next js scrollRestoration

김형석·2023년 6월 30일
1

Next.js

목록 보기
1/1
post-thumbnail

트러블 슈팅

next js 에서 뒤로가기시 스크롤을 기억하는 이슈가 있었고.
때문에, 뒤로가기 동작시 스크롤이 내려갔다가 혹은 올라갔다가 뒤로가기가 진행되는.
유저 입장에서 보기 다소 불편감을 줄 수 있는 동작을 하고 있었다.

scrollRestoration

https://github.com/vercel/next.js/commit/38bd1a024cb25923d8ea15f269a7294d073684d8

experimental : 실험적

next.config.js

experimental: {
    scrollRestoration: true,
  },

해당 코드를 사용하면, 위의 링크를 따라가보면

866 line에 process.env.__NEXT_SCROLL_RESTORATION에 true값이 들어가게 되고

100 line의 manualScrollRestoration에 그에 따른 값이 들어가게된다. (true)

scrollRestoration:true로 설정했을경우 263라인의 코드가 실행되게 되어서

//스크롤 복원 비활성화
window.history.scrollRestoration = 'manual';

가 되게된다. 즉 브라우저의 기본 history.scrollRestoration을 막아두어서 브라우저가 스크롤에는 관여 안하도록 하게하고.

const debouncedScrollSave = () => {
            if (scrollDebounceTimeout) clearTimeout(scrollDebounceTimeout)

            scrollDebounceTimeout = setTimeout(() => {
              const { url, as: curAs, options } = history.state
              this.changeState(
                'replaceState',
                url,
                curAs,
                Object.assign({}, options, {
                  _N_X: window.scrollX,
                  _N_Y: window.scrollY,
                })
              )
            }, 10)
          }

여기에서 저장한 스크롤을 가지고.

if (process.env.__NEXT_SCROLL_RESTORATION) {
              if (manualScrollRestoration && '_N_X' in options) {
                window.scrollTo(options._N_X, options._N_Y)
              }
            }
            Router.events.emit('routeChangeComplete', as)

            return resolve(true)

라우터를 업데이트하는 시점에 보내주게 된다.

결과

현재 프로젝트에 적용한 결과 정상적으로 잘 작동하고 있다.

마치며

어디까지나 실험적 기능이기 때문에 좀 더 자세히 들여다 보아야 할 것 같다.
휴일인데도 도움을 주신 회사 동료분께 무한한 감사를 드리며 글을 마무리 하겠다.

참고

profile
코드로 소통하기 위해 힘쓰는 프론트엔드 개발자 입니다.

0개의 댓글