Created
June 24, 2024 18:32
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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