Last active
November 13, 2019 14:53
-
-
Save ahtcx/656ad3cd592d99e0371c2a65acc2a649 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useRef } from 'react' | |
export interface ScrollEvents<Event extends any> { | |
scrollStart?: (event: Event) => void | |
scrollStop?: (event: Event) => void | |
scroll?: (event: Event) => void | |
} | |
export const useScrollEvents = <Event extends any = React.UIEvent>( | |
scrollEvents: ScrollEvents<Event>, | |
timeout: number = 200, | |
) => { | |
const timeoutIdRef = useRef<number | void>() | |
const scrollStarted = useRef(false) | |
useEffect(() => { | |
return () => { | |
if (timeoutIdRef.current) { | |
timeoutIdRef.current = window.clearTimeout(timeoutIdRef.current) | |
} | |
} | |
}, []) | |
const handleScroll = (event: Event) => { | |
if (timeoutIdRef.current) { | |
timeoutIdRef.current = window.clearTimeout(timeoutIdRef.current) | |
} | |
if (!timeoutIdRef.current) { | |
if (!scrollStarted.current) { | |
scrollEvents.scrollStart?.(event) | |
scrollStarted.current = true | |
} | |
timeoutIdRef.current = window.setTimeout(() => { | |
scrollEvents.scrollStop?.(event) | |
scrollStarted.current = false | |
}, timeout) | |
} | |
scrollEvents.scroll?.(event) | |
} | |
return handleScroll | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment