useIsScrolled
hookas/use-is-scrolledFreeHook
A hook to check if an element is scrolled
Install it
npx shadcn@latest add https://hookas.letstri.dev/r/use-is-scrolled.jsonSource
1'use client'23import * as React from 'react'45export type ScrollDirection = 'vertical' | 'horizontal' | 'both'67export function useIsScrolled(8 ref: React.RefObject<Element | null>,9 {10 threshold = 10,11 initial = false,12 direction = 'both',13 }: { threshold?: number, initial?: boolean, direction?: ScrollDirection } = {},14) {15 const [isScrolled, setIsScrolled] = React.useState(initial)1617 const handleScrollEvent = React.useEffectEvent(() => {18 const element = ref.current1920 if (!element)21 return2223 const scrollTop = element.scrollTop24 const scrollLeft = element.scrollLeft2526 let scrolled = false27 if (direction === 'vertical') {28 scrolled = scrollTop > threshold29 }30 else if (direction === 'horizontal') {31 scrolled = scrollLeft > threshold32 }33 else {34 scrolled = scrollTop > threshold || scrollLeft > threshold35 }3637 setIsScrolled(scrolled)38 })3940 React.useEffect(() => {41 const element = ref.current4243 if (!element)44 return4546 const abortController = new AbortController()4748 element.addEventListener('scroll', handleScrollEvent, { passive: true, signal: abortController.signal })4950 return () => {51 abortController.abort()52 }53 }, [ref, threshold, direction])5455 return isScrolled56}
Files it writes
More from hookas
All 30 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| useAsyncEffectuse-async-effect | hookas | Hooks | Free | no deps | |
| useClickOutsideuse-click-outside | hookas | Hooks | Free | no deps | |
| useDebounceCallbackuse-debounced-callback | hookas | Hooks | Free | no deps | |
| useDebounceMemouse-debounced-memo | hookas | Hooks | Free | no deps | |
| useDebounceStateuse-debounced-state | hookas | Hooks | Free | no deps | |
| useElementSizeuse-element-size | hookas | Hooks | Free | no deps | |
| useFullscreenuse-fullscreen | hookas | Hooks | Free | no deps | |
| useIntervaluse-interval | hookas | Hooks | Free | no deps |
