Skip to content

Instantly share code, notes, and snippets.

@ahtcx
Last active November 13, 2019 14:53
Show Gist options
  • Save ahtcx/656ad3cd592d99e0371c2a65acc2a649 to your computer and use it in GitHub Desktop.
Save ahtcx/656ad3cd592d99e0371c2a65acc2a649 to your computer and use it in GitHub Desktop.
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