src/shared/ui/Header/useToggleHeaderOnScroll.js   A
last analyzed

Complexity

Total Complexity 1
Complexity/F 0

Size

Lines of Code 34
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 1
eloc 30
mnd 1
bc 1
fnc 0
dl 0
loc 34
rs 10
bpm 0
cpm 0
noi 0
c 0
b 0
f 0
1
import { useLayoutEffect, useRef, useState } from 'react'
2
import { throttle } from 'shared/lib/throttle'
3
4
const useToggleHeaderOnScroll = () => {
5
  const [visible, setVisible] = useState(1)
6
  const prevScrollPos = useRef()
7
  const currScrollPos = useRef()
8
  const HEADER_HEIGHT = 60
9
10
  useLayoutEffect(() => {
11
    prevScrollPos.current = window.pageYOffset
12
13
    const handleScroll = () => {
14
      currScrollPos.current = window.pageYOffset
15
16
      prevScrollPos.current > currScrollPos.current || 
17
        prevScrollPos.current < HEADER_HEIGHT
18
        ? setVisible(1)
19
        : setVisible(0)
20
21
      prevScrollPos.current = currScrollPos.current
22
    }
23
24
    const throttledHandleScroll = throttle(handleScroll, 200)
25
    window.addEventListener('scroll', throttledHandleScroll)
26
    
27
    return () => window.removeEventListener('scroll', throttledHandleScroll)
28
  })
29
30
  return visible
31
}
32
33
export { useToggleHeaderOnScroll }
34