Skip to content

Commit

Permalink
fix: add additional ref check on clean up
Browse files Browse the repository at this point in the history
  • Loading branch information
James committed Jun 17, 2019
1 parent b3ba702 commit d18d2d8
Showing 1 changed file with 19 additions and 18 deletions.
37 changes: 19 additions & 18 deletions src/useScrolling.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,28 @@ import { RefObject, useEffect, useState } from 'react';
const useScrolling = (ref: RefObject<HTMLElement>): boolean => {
const [scrolling, setScrolling] = useState<boolean>(false);

useEffect(
() => {
if (ref.current) {
let scrollingTimeout;
useEffect(() => {
if (ref.current) {
let scrollingTimeout;

const handleScrollEnd = () => {
setScrolling(false);
};
const handleScrollEnd = () => {
setScrolling(false);
};

const handleScroll = () => {
setScrolling(true);
clearTimeout(scrollingTimeout);
scrollingTimeout = setTimeout(() => handleScrollEnd(), 150);
};
const handleScroll = () => {
setScrolling(true);
clearTimeout(scrollingTimeout);
scrollingTimeout = setTimeout(() => handleScrollEnd(), 150);
};

ref.current.addEventListener('scroll', handleScroll, false);
return () => ref.current.removeEventListener('scroll', handleScroll, false);
}
},
[ref.current],
);
ref.current.addEventListener('scroll', handleScroll, false);
return () => {
if (ref.current) {
ref.current.removeEventListener('scroll', handleScroll, false);
}
};
}
}, [ref.current]);

return scrolling;
};
Expand Down

0 comments on commit d18d2d8

Please sign in to comment.