I am using react-native with react-native-navigation. I would like to reload data when a component is shown. The component is shown when a user clicks on a tab navigation button
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.