React: check if user is at the bottom of the viewport
22 August 2024 (Updated 22 August 2024)
import throttle from 'lodash/throttle'
import { useCallback, useEffect, useState } from 'react'
export function useIsBottomOfViewport() {
const [isBottomOfViewport, setIsBottomOfViewport] = useState(false)
const checkIfBottomOfViewport = useCallback(() => {
return throttle(() => {
const isBottom =
window.innerHeight + Math.round(window.scrollY) >=
document.body.offsetHeight
setIsBottomOfViewport(isBottom)
}, 500)
}, [])
useEffect(() => {
window.addEventListener('scroll', checkIfBottomOfViewport)
return () => {
window.removeEventListener('scroll', checkIfBottomOfViewport)
}
}, [checkIfBottomOfViewport])
return isBottomOfViewport
}
Tagged:
React