UseScrollPosition
guarahooks/use-scroll-positionFreeHook
Tracks the current scroll position of the page.
Install it
npx shadcn@latest add https://guarahooks.com/r/use-scroll-position.jsonSource
1'use client';23import { useCallback, useEffect, useState } from 'react';45export type ScrollPosition = {6 x: number;7 y: number;8};910export type UseScrollPositionOptions = {11 onChange?: (x: number, y: number) => void;12};1314export function useScrollPosition(15 options: UseScrollPositionOptions = {},16): ScrollPosition {17 const isBrowser = typeof window !== 'undefined';18 const { onChange } = options;1920 const [scrollPosition, setScrollPosition] = useState<ScrollPosition>({21 x: isBrowser ? window.scrollX : 0,22 y: isBrowser ? window.scrollY : 0,23 });2425 const handleScroll = useCallback(() => {26 const x = window.scrollX;27 const y = window.scrollY;28 setScrollPosition({ x, y });29 if (onChange) {30 onChange(x, y);31 }32 }, [onChange]);3334 useEffect(() => {35 if (!isBrowser) {36 return;37 }38 window.addEventListener('scroll', handleScroll, { passive: true });39 // Initialize position on mount40 handleScroll();41 return () => {42 window.removeEventListener('scroll', handleScroll);43 };44 }, [handleScroll, isBrowser]);4546 return scrollPosition;47}
Files it writes
More from guarahooks
All 100 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| UseAbortControlleruse-abort-controller | guarahooks | Hooks | Free | no deps | |
| UseArrayStateuse-array-state | guarahooks | Hooks | Free | no deps | |
| UseAxiosuse-axios | guarahooks | Hooks | Free | no deps | |
| UseBatteryStatususe-battery-status | guarahooks | Hooks | Free | no deps | |
| UseBetterAuthuse-better-auth | guarahooks | Hooks | Free | no deps | |
| UseClickOutsideuse-click-outside | guarahooks | Hooks | Free | no deps | |
| UseConfirmuse-confirm | guarahooks | Hooks | Free | no deps | |
| UseCookieuse-cookie | guarahooks | Hooks | Free | no deps |
