Search code examples
react-nativereact-native-navigation

How to remove event listener of react-navigation in react native?


I want to detect focus change on naviagtion in React Native. I am using class components but now days RN community flooded with functional component .

Here is the snippet from @react-naviagtion

function Profile({ navigation }) {
    React.useEffect(() => {
      const unsubscribe = navigation.addListener('focus', () => {
        // Screen was focused
        // Do something
      });
  
      return unsubscribe;
    }, [navigation]);
  
    return (
        <>
            <Text>tedtx</Text>
        </>
    );
  }

I have used in class component and it works well no memory leak warning yet but I don't know if this is a way to do or not.

    componentDidMount(){
        
        this.state.focusListener = this.props.nav.navigation.addListener('focus',()=>{
            log('route ',this.props)
        })
         // should I return here
    }
   componentWillUnmount(){
       // or should i something here?
       // this.props.nav.navigation.removeListener(this.state.focusEvent)
      //above does not give error but not removing listener
   }

I noticed that reloading the metro remove listeners. As I save the file (Hot Reloading) and try to invoke the the listeners on focus it actually increases. It increase by one each time I hot reload. It seems that listeners are not getting removed.


Solution

  • you can try this

    class Profile extends React.Component {
      componentDidMount() {
        this._unsubscribe = navigation.addListener('focus', () => {
          // do something
        });
      }
    
      componentWillUnmount() {
        this._unsubscribe();
      }
    
      render() {
        // Content of the component
      }
    }
    

    react navigation events: https://reactnavigation.org/docs/navigation-events/