UseScrollLock
guarahooks/use-scroll-lockFreeHook
Lock and unlock scrolling on an element or the page
Install it
npx shadcn@latest add https://guarahooks.com/r/use-scroll-lock.jsonSource
1'use client';23import {4 MutableRefObject,5 RefObject,6 useCallback,7 useEffect,8 useRef,9 useState,10} from 'react';1112export interface UseScrollLockReturn {13 isLocked: boolean;14 lock: () => void;15 unlock: () => void;16 toggle: () => void;17}1819export function useScrollLock<T extends HTMLElement = HTMLElement>(20 ref?: RefObject<T> | MutableRefObject<T | null>,21): UseScrollLockReturn {22 const refCached = useRef<23 RefObject<T> | MutableRefObject<T | null> | undefined24 >(ref);2526 useEffect(() => {27 refCached.current = ref;28 }, [ref]);2930 const [isLocked, setIsLocked] = useState<boolean>(false);31 const originalOverflow = useRef<string>('');3233 const getTarget = useCallback((): HTMLElement => {34 const currentRef = refCached.current;35 const el = currentRef?.current ?? null;36 return (el as HTMLElement) || document.body;37 }, []);3839 const lock = useCallback(() => {40 if (!isLocked) {41 const target = getTarget();42 originalOverflow.current = target.style.overflow;43 target.style.overflow = 'hidden';44 setIsLocked(true);45 }46 }, [getTarget, isLocked]);4748 const unlock = useCallback(() => {49 if (isLocked) {50 const target = getTarget();51 target.style.overflow = originalOverflow.current;52 setIsLocked(false);53 }54 }, [getTarget, isLocked]);5556 const toggle = useCallback(() => {57 isLocked ? unlock() : lock();58 }, [isLocked, lock, unlock]);5960 // Restore on unmount61 useEffect(() => {62 return () => {63 const target = getTarget();64 target.style.overflow = originalOverflow.current;65 };66 }, [getTarget]);6768 return { isLocked, lock, unlock, toggle };69}
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 |
