react-native-ui-lib
Version:
[](https://stand-with-ukraine.pp.ua)
48 lines (47 loc) • 1.31 kB
JavaScript
import { useState, useCallback, useRef } from 'react';
/**
* @description: A hook that tracks scroll direction to toggle visibility (e.g., for hiding a footer on scroll).
* @example: const {onScroll, visible} = useScrollToHide();
*/
const useScrollToHide = (props = {}) => {
const {
scrollingThreshold = 0
} = props;
const [visible, setVisible] = useState(true);
const prevContentOffset = useRef(0);
const onScroll = useCallback(event => {
const {
nativeEvent: {
contentOffset: {
y: currentOffset
},
contentSize: {
height: contentHeight
},
layoutMeasurement: {
height: layoutHeight
}
}
} = event;
// Ignore bounces (iOS)
if (currentOffset < 0 || currentOffset > contentHeight - layoutHeight) {
return;
}
const diff = currentOffset - prevContentOffset.current;
if (Math.abs(diff) > scrollingThreshold) {
if (diff > 0 && visible) {
// Scrolling Down -> Hide
setVisible(false);
} else if (diff < 0 && !visible) {
// Scrolling Up -> Show
setVisible(true);
}
prevContentOffset.current = currentOffset;
}
}, [visible, scrollingThreshold]);
return {
onScroll,
visible
};
};
export default useScrollToHide;