Search code examples
react-nativescrollviewuse-effectuse-ref

React native reset ScrollView to the top after render


I am trying to reset the Scrollview back to the top when user navigates away and then back to the screen. Currently when I scroll down and click on a different tab away from the screen , when I come back to the previous screen, the scroll is at the same position where I left it in the last scroll. My solution with hooks useRef and useEffect it does not seem to be working and I can not get the current position of the scroll either. You can view a prototype of this effort on snack.expo:

https://snack.expo.io/@flag81/scrolltotop

Thanks is advance.


Solution

  • If you are using react-navigation (as it most likely is), I would use react-navigation's hook useIsFocused

    https://reactnavigation.org/docs/use-is-focused/

    In your tab import the hook

    import { useIsFocused } from "@react-navigation/native";
    

    Then use a ref for your ScrollView

    const scrollViewRef = useRef<ScrollView>();
    

    Then use the hook together with useEffect to reset

    const isFocused = useIsFocused();
    useEffect(() => {
        if (isFocused) {
            scrollViewRef.current?.scrollTo(0, 0, true);
        }
    }, [isFocused]);