DEV Community

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

Posted on • Edited on

1

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay