useRef를 활용하여 무한스크롤 구현

D9·2022년 9월 12일
0

TIL

목록 보기
6/6

이번 과제에서 react query를 활용하여 무한스크롤을 구현하는 과제가 있었다.

useInfinity 쿼리를 활용하여 페이지가 증가할 때 마다 추가 데이터를 불러오는거는 문제가 없었는데

스크롤의 최하단에 도달할 때 fetch가 작동하게 하는 방법을 찾아보니

'react-intersection-observer'이란 라이브러리를 사용하는 방법이 있었는데,

내가 잘못한건지 모르겠지만 react-intersection-observer을 사용하니 추가렌더링이 발생하였다.

react-intersection-observer의 useInView 에서 useState를 활용해서 렌더링이 일어나는 것 같았다.

일단 추가 렌더링을 막기위해서, useInView가 아니라 순수하게 스크롤 최하단에 도달하였을 때

이벤트가 발생하도록 하는 로직을 찾아보았다.

const bottomWindow = new IntersectionObserver(callback,option)
      
bottomWindow.observe(observerTargetEl.current)

new IntersectionObserver() 를 통해 bottomWindow라는 인스턴스를 생성하고,

bottomWindow.observe(관찰할 Element) 로 bottomWindow의 인스턴스에 관찰할 element를 추가한다

callback 함수는 entries와 observe 두개의 인자를 받는 함수를 가진다

observe를 통해 등록된 element만큼 entries에 배열로 해당 element가 추가된다.

예를들면

const bottomWindow = new IntersectionObserver(
      (entries, observe) => {},option)
      
      
bottomWindow.observe(observerTargetEl.current)
bottomWindow.observe(observerTargetNextEl.current)

의 경우 entries를 console로 찍어보면 다음과같이 표시된다.

boundingClientRect는 해당 element의 전체 사각형 영역이고,
intersectionRatio 는 교차되는 비율
intersectionRect 는 교차되는 element의 사각영역
isIntersection은 화면에 해당 element가 보이는 여부를 나타낸다.

또한 option에서는 threshold 를 통해서 element가 몇 %일때 observe를 실행시킬건지를 지정할 수 있다.

따라서 다음의 코드는

 const bottomWindow = new IntersectionObserver(
      entries => {
        if (entries[0].isIntersecting) {  
          fetchNextPage()
        }
        // entries[0] => 관찰할 element가 등록되고, 교차되었을때 fetchNextPage()를 실행 //
      },
      { threshold: 0.7 }, // element가 70%이상 교차되었을때 observer 실행 //
    )
bottomWindow.observe(observerTargetEl.current) 
//useRef를 활용하여 DOM에 접근하여 observe로 등록//

이렇게 표현되어진다.

intersectionObserver를 활용하여, dom에 접근하여 해당 화면에 보여지는 상태에 따른 작업을 진행할 수 있었다.

profile
새로운 시작

0개의 댓글