The currently accepted answer suggests a react-navigation solution, not react-native-navigation (RNN), so I'll go ahead and give my two cents.
As Stephen Liu points out in his answer, RNN provides screen lifecycle methods that fire when a component appears (componentDidAppear
) and disappears (componentDidDisappear
).
Stephen's answer works for a class component, however in the age of hooks I prefer function components. So this is how to use RNN's screen lifecycle methods in a function component:
import React, { useEffect } from 'react'
import { Navigation } from 'react-native-navigation'
const MyComponent = ({ componentId }) => {
useEffect(() => {
const navListener = Navigation.events().bindComponent(this, componentId)
// remove the listener during cleanup
return () => {
navListener.remove()
}
}, [componentId])
this.componentDidAppear = () => {
// do stuff when component appears
}
this. componentDidDisappear = () => {
// do stuff when component disappears
}
}
Important: MyComponent
needs a componentId
prop, which is injected automatically if it's a registered RNN screen or modal (Navigation.registerComponent
). You can also manually pass it down from a screen component to the child where you need it.
Bonus: useComponentDidAppear
hook
I use RNN's componentDidAppear fairly often in my project, so I made a custom hook to reuse it super easily throughout my function components:
export const useComponentDidAppear = (componentId, callback) => {
useEffect(() => {
const navListener = Navigation.events().bindComponent(this, componentId)
return () => {
navListener.remove()
}
}, [componentId])
this.componentDidAppear = () => {
callback()
}
}
// then use it like this
const SomeScreen = ({ componentId }) => {
useComponentDidAppear(componentId, () => {
// do stuff when the component appears!
})
}