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
react navigation events: https://reactnavigation.org/docs/navigation-events/
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