강의

멘토링

로드맵

Inflearn brand logo image

인프런 커뮤니티 질문&답변

Choi Boo님의 프로필 이미지
Choi Boo

작성한 질문수

[리뉴얼] React로 NodeBird SNS 만들기

쿼리스트링과 lastId 방식

scroll throttle 문제일까요?

작성

·

541

0

useEffect(() => {
const onScroll = () => {
/*
window.scrollY : 현재 스크롤 위치
document.documentElement.clientHeight : 현재 보고 있는 브라우저의 높이
document.documentElement.scrollHeight : 총 높이
*/
// 스크롤 맨 아래에서 살짝 위에 있을 때 true
const heightCheck: boolean =
window.scrollY + document.documentElement.clientHeight >
document.documentElement.scrollHeight - 300;

if (heightCheck) {
if (hasMorePosts && !loadPostLoading) {
console.log('wow');
const lastId: number = mainPosts[mainPosts.length - 1]?.id;
dispatch(loadPostAction(lastId));
}
}
};
window.addEventListener('scroll', _throttle(onScroll, 500));
return () => {
window.removeEventListener('scroll', onScroll);
};
}, [hasMorePosts, loadPostLoading, mainPosts]);

saga에서는 throttle이 내장 되어서 사용하기 편한데

saga를 안 쓰고 lodash의 throttle을 이용해서 하려고 합니다.

그런데 데이터의 총 개수가  15개라 하면

처음 로드할 때 10개(1회 요청), 스크롤할 때 5개(1회 요청) 나와야 정상이잖아요?

그런데 처음 스크롤할 때 2회 요청,

그 다음 4회 요청, 또 내리면 7회 요청 이런식으로 증가하게 됩니다.

throttle이 제대로 안 먹히는건가요?

질문 글 보면 '박민호'님 증상이랑 비슷한 것 같습니다.

답변 2

1

제로초(조현영)님의 프로필 이미지
제로초(조현영)
지식공유자

_.throttle(scroll, 500) 을 useEffect에 넣으면 hasMorePosts, loadPostLoading, mainPosts가 바뀔 때마다 함수가 새로 생성됩니다. 함수가 새로 생성되면 _.throttle이 과거 기록을 기억 못합니다.

_.throttle(scroll, 500)와 scroll을 useEffect 바깥으로 꺼낸 뒤 useMemo로 감싸서 고정해둔 뒤에 재사용해야 합니다.

0

Choi Boo님의 프로필 이미지
Choi Boo
질문자

useEffect(() => {
window.addEventListener('scroll', scrollHandler);
return () => {
window.removeEventListener('scroll', scrollHandler);
};
}, [hasMorePosts, loadPostLoading, mainPosts]);

const scrollHandler = _throttle(onScroll, 500);
// const scrollHandler = useMemo(() => _throttle(onScroll, 500), []);

이런식으로 분리를 해봤습니다.

useMemo를 쓰지 않았을 때는 스크롤당 1회씩 요청과 hasmorePosts가 제대로 적용되어 마지막일 때는 요청을 보내지 않으나,

useMemo를 사용할 때는 스크롤을 내리면 계속 요청을 보내는데 useMemo를 작성하는 방법이 틀렸나요?

디펜던시를 useEffect에 있는 걸 useMemo로 옮겨도 똑같습니다..

Choi Boo님의 프로필 이미지
Choi Boo

작성한 질문수

질문하기