blob: 19bfebc0aa47b0e7344c66e8be2fc6a745856a9d (
plain)
| 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
 | import { useCallback, useEffect, useState } from 'react';
/**
 * Retrieve the scrollbar width of the window.
 *
 * @returns {number} The scrollbar width.
 */
export const getScrollbarWidth = (): number => {
  const defaultWidth = 15;
  if (typeof window === 'undefined') return defaultWidth;
  return window.document.body.clientWidth
    ? window.innerWidth - window.document.body.clientWidth
    : 0;
};
/**
 * React hook to retrieve the current scrollbar width of the window.
 *
 * @returns {number} The scrollbar width.
 */
export const useScrollBarWidth = (): number => {
  const [scrollbarWidth, setScrollbarWidth] = useState(0);
  const updateScrollbarWidth = useCallback(() => {
    setScrollbarWidth(getScrollbarWidth());
  }, []);
  useEffect(() => {
    updateScrollbarWidth();
    window.addEventListener('resize', updateScrollbarWidth);
    window.addEventListener('orientationchange', updateScrollbarWidth);
    return () => {
      window.removeEventListener('resize', updateScrollbarWidth);
      window.removeEventListener('orientationchange', updateScrollbarWidth);
    };
  }, [updateScrollbarWidth]);
  return scrollbarWidth;
};
 |