Reading time: < 1 minute
If we want to refresh a screen when returning from another screen using React Native, we have to do the following:

First, we import react-navigation
import { useFocusEffect } from '@react-navigation/native';
Then, we add it in our render:
useFocusEffect(
React.useCallback(() => {
}, [])
);
Inside the React.useCallback block, we perform the calls that we want to refresh. In the [] brackets, we can put the variable that changes when returning from another screen, for example, [code].
useFocusEffect(
React.useCallback(() => {
console.log("Code changes to: " + code)
}, [code])
);
Another option, or if we have different navigation:
useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
console.log('In Navigation Add Listener Block');
refresh();
return unsubscribe;
}, [navigation]);
}, [navigation]);
This will subscribe to changes made by navigation and only invoke useEffects when there are changes in navigation.
If we have two navigation, we can duplicate the code as follows:
useEffect(() => {
const unsubscribe = initialNavigation.addListener('focus', () => {
//console.log('In Initial Navigation Add Listener Block');
refresh();
return unsubscribe;
}, [initialNavigation]);
}, [initialNavigation]);
useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
//console.log('In Navigation Add Listener Block');
refresh();
return unsubscribe;
}, [navigation]);
}, [navigation]);
