UNPKG

beautiful-react-hooks

Version:

A collection of beautiful (and hopefully useful) React hooks to speed-up your components and hooks development

28 lines (27 loc) 1.12 kB
import { useCallback } from 'react'; import createHandlerSetter from './factory/createHandlerSetter'; import safeHasOwnProperty from './shared/safeHasOwnProperty'; import useEvent from './useEvent'; /** * Accepts an HTML Element ref, then returns a function that allows you to handle the infinite * scroll for that specific element. */ const useInfiniteScroll = (ref, delay = 250) => { const onScroll = useEvent(ref, 'scroll', { passive: true }); const [onScrollEnd, setOnScrollEnd] = createHandlerSetter(); if (ref && !safeHasOwnProperty(ref, 'current')) { throw new Error('Unable to assign any scroll event to the given ref'); } const handleScroll = useCallback(({ target }) => { const el = target; if (el) { const isBottom = el.scrollHeight - el.scrollTop === el.clientHeight; if (isBottom && onScrollEnd.current && typeof onScrollEnd.current === 'function') { setTimeout(onScrollEnd.current, delay); } } }, []); onScroll(handleScroll); return setOnScrollEnd; }; export default useInfiniteScroll;