useScrollLock

2023-10-12

1

useScrollLock

주로 모달과 같은 팝업이 뜰 때 스크롤을 이벤트를 막아주는 훅으로 사용

Hooks

tsx
1import { useCallback, useRef } from 'react';
2
3type CSSProperties = {
4  [key: string]: string | number;
5};
6
7export default function useScrollLock() {
8  const scrollRef = useRef(0);
9
10  const modifyBodyStyle = useCallback((style: CSSProperties) => {
11    const $body = document.querySelector('body');
12    if ($body) {
13      Object.assign($body.style, style);
14    } else {
15      console.error('document.body is not defined');
16    }
17  }, []);
18
19  const lockScroll = () => {
20    scrollRef.current = window.scrollY;
21    modifyBodyStyle({
22      overflowY: 'hidden',
23      position: 'fixed',
24      top: `-${scrollRef.current}px`,
25      left: '0',
26      right: '0',
27    });
28  };
29
30  const unlockScroll = () => {
31    modifyBodyStyle({
32      overflowY: '',
33      position: '',
34      top: '',
35      left: '',
36      right: '',
37    });
38
39    window.scrollTo({ left: 0, top: scrollRef.current, behavior: 'instant' });
40  };
41
42  return {
43    lockScroll,
44    unlockScroll,
45  };
46}

Usage (Modal)

tsx
1export default function Modal() {
2  comst {lockScroll, unlockScroll} = useScrollLock();
3
4  useEffect(() => {
5    lockScroll();
6
7    return () => {
8      unlockScroll();
9    }
10  }, [])
11
12
13  return (<>...</>)
14}