4

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.

3 Answers 3

6

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/

Sign up to request clarification or add additional context in comments.

Comments

5

I did this with with function components and hooks...


  const [canGoBack, setCanGoBack] = useState(false)

  useEffect(() => {
    const listenerUnsubscribe = navigation.addListener('focus', () => {
      setCanGoBack(navigation.canGoBack())
    })
    return () => listenerUnsubscribe()
  }, [navigation])

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.