UNPKG

1.61 kBJavaScriptView Raw
1'use client';
2
3import * as React from 'react';
4function defaultTrigger(store, options) {
5 const {
6 disableHysteresis = false,
7 threshold = 100,
8 target
9 } = options;
10 const previous = store.current;
11 if (target) {
12 // Get vertical scroll
13 store.current = target.pageYOffset !== undefined ? target.pageYOffset : target.scrollTop;
14 }
15 if (!disableHysteresis && previous !== undefined) {
16 if (store.current < previous) {
17 return false;
18 }
19 }
20 return store.current > threshold;
21}
22const defaultTarget = typeof window !== 'undefined' ? window : null;
23export default function useScrollTrigger(options = {}) {
24 const {
25 getTrigger = defaultTrigger,
26 target = defaultTarget,
27 ...other
28 } = options;
29 const store = React.useRef();
30 const [trigger, setTrigger] = React.useState(() => getTrigger(store, other));
31 React.useEffect(() => {
32 const handleScroll = () => {
33 setTrigger(getTrigger(store, {
34 target,
35 ...other
36 }));
37 };
38 handleScroll(); // Re-evaluate trigger when dependencies change
39 target.addEventListener('scroll', handleScroll, {
40 passive: true
41 });
42 return () => {
43 target.removeEventListener('scroll', handleScroll, {
44 passive: true
45 });
46 };
47 // See Option 3. https://github.com/facebook/react/issues/14476#issuecomment-471199055
48 // TODO: uncomment once we enable eslint-plugin-react-compiler // eslint-disable-next-line react-compiler/react-compiler
49 // eslint-disable-next-line react-hooks/exhaustive-deps
50 }, [target, getTrigger, JSON.stringify(other)]);
51 return trigger;
52}
\No newline at end of file