DEV Community

Nguyễn Hữu Hiếu
Nguyễn Hữu Hiếu

Posted on • Updated on

React Native Navigation: useFocus to reload the screen every time back

  • Custom focus when using ReactNativeNavigation
import {useNavigation} from '@react-navigation/native';
import {useState, useEffect} from 'react';

export const useFocus = () => {
  const navigation = useNavigation();
  const [isFocused, setIsFocused] = useState(false);
  const [focusCount, setFocusCount] = useState(0);
  const isFirstTime = focusCount === 1;

  useEffect(() => {
    const unsubscribeFocus = navigation.addListener('focus', () => {
      setIsFocused(true);
      setFocusCount(prev => prev + 1);
    });
    const unsubscribeBlur = navigation.addListener('blur', () => {
      setIsFocused(false);
    });

    return () => {
      unsubscribeFocus();
      unsubscribeBlur();
    };
  });

  return {isFocused, isFirstTime, focusCount};
};

Enter fullscreen mode Exit fullscreen mode

How to use

const App = () => {
   const {focusCount, isFocused} = useFocus();

   useEffect(() => {
        if (focusCount === 1 && isFocused) {
            // this is the first time focus => init screen here
        }
   });

   useEffect(() => {
        if (focusCount > 1 && isFocused) {
            // trigger when you navigate back from another screen
            // you can background reload data here ...
        }
   });


}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)