skip to Main Content

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.

2

Answers


  1. 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/

    Login or Signup to reply.
  2. componentDidMount(){
      this.focusListener = this.props.navigation.addListener('focus',() => {
        log('route ',this.props);
      });
      // should I return here
      // nothing to return
    }
    
    componentWillUnmount() {
      this.focusListener();
    }
    

    Yes, most of the examples show usage in functional component but there is an example in docs showing how to setup/ remove navigation listeners in class component

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search