Skip to content

Instantly share code, notes, and snippets.

@johhansantana
Created June 24, 2024 18:32
Show Gist options
  • Save johhansantana/5dccb91eb1ed5a54ef5ff46b3d52fc90 to your computer and use it in GitHub Desktop.
Save johhansantana/5dccb91eb1ed5a54ef5ff46b3d52fc90 to your computer and use it in GitHub Desktop.
This custom react native hook detects when a ScrollView reaches the end of its scroll so you can do stuff like infinite scroll and what not
import { useCallback, useState } from "react";
import { NativeScrollEvent, NativeSyntheticEvent } from "react-native";
interface UseDetectScrollEndProps {
onEndReached: () => void;
offset?: number;
}
const useDetectScrollEnd = ({
onEndReached,
offset = 20,
}: UseDetectScrollEndProps) => {
const [isEndReached, setIsEndReached] = useState(false);
const onScroll = useCallback(
(event: NativeSyntheticEvent<NativeScrollEvent>) => {
const { nativeEvent } = event;
const { layoutMeasurement, contentOffset, contentSize } =
nativeEvent;
const isEnd =
layoutMeasurement.height + contentOffset.y >=
contentSize.height - offset;
if (isEnd && !isEndReached) {
setIsEndReached(true);
onEndReached();
} else if (!isEnd) {
setIsEndReached(false);
}
},
[isEndReached, onEndReached, offset]
);
return { onScroll };
};
export { useDetectScrollEnd };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment