Contents
Introduction
This is an Example to Refresh the Previous Screen after Going Back to the old Screen in React Native using React Navigation. If you are familiar with the navigation in React Native then I hope you very well know React Navigation. We have also used the same navigator for this example.
While working with multiple screens we usually switch between screens and sometimes wants to refresh the previous screen as the result set should change. If we talk about React Navigation it does not provide the default refresh facility as in most of the cases we do not want to rerender the view. So we have to add some extra things to refresh the previous screens while going back.
To refresh the previous screen when going back
As a JavaScript developer, we very well know about the listeners. In this case, we will also use a listener called focus
to find the current state of the Screen/ Activity.
To apply focus
listener
const unsubscribe = navigation.addListener('focus', () => {
// Do whatever you want
});
To remove the listener
unsubscribe;
In this example, we will create 2 Screens FirstPage and SecondPage and will make a count on both the screens to see whether it is refreshing or not. If we run the application without the didFocus listener we have no way to reset the counter when coming back to FirstPage so counter will increase as we are unable to refresh the screen but in other condition when we apply the didFocus listener we can reset the counter or basically we can say that we can refresh the screen. So Let’s get Started with example.
To Make a React Native App
Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react-native init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli
command line utility. Open the terminal and go to the workspace and run
npm install -g react-native-cli
Run the following commands to create a new React Native project
react-native init ProjectName
If you want to start a new project with a specific React Native version, you can use the --version argument:
react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next
This will make a project structure with an index file named App.js in your project directory.
Installation of Dependencies
To navigate between screens we need to add react-navigation
and other supporting dependencies.
To install the dependencies open the terminal and jump into your project
cd ProjectName
1. Install react-navigation
npm install @react-navigation/native --save
2. Other supporting libraries react-native-gesture-handler
, react-native-reanimated
, react-native-screens
and react-native-safe-area-context
and @react-native-community/masked-view
npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view --save
3. For the Stack Navigator install
npm install @react-navigation/stack --save
Note: When you use a navigator (such as stack navigator), you’ll need to follow the installation instructions of that navigator for any additional dependencies. If you’re getting an error “Unable to resolve module”, you need to install that module in your project.
You might get warnings related to peer dependencies after installation. They are usually caused by incorrect version ranges specified in some packages. You can safely ignore most warnings as long as your app builds.
CocoaPods Installation
Please use the following command to install CocoaPods
npx pod-install ios
To finalize the installation of react-native-gesture-handler
, add the following at the top (make sure it’s at the top and there’s nothing else before it) of your entry files, such as index.js or App.js:
import 'react-native-gesture-handler';
Note: If you skip this step, your app may crash in production even if it works fine in development.
Project Structure
To start with this Example you need to create a directory named pages in your project and create two files FirstPage.js and SecondPage.js
Code
Now Open App.js in any code editor and replace the code with the following code
App.js
// Refresh Previous Screen after Going Back in React Navigation
// https://aboutreact.com/refresh-previous-screen-react-navigation/
import 'react-native-gesture-handler';
import React from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack';
import FirstPage from './pages/FirstPage';
import SecondPage from './pages/SecondPage';
const Stack = createStackNavigator();
const App = () => {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="FirstPage">
<Stack.Screen
name="FirstPage"
component={FirstPage}
options={{
title: 'First Page', //Set Header Title
headerStyle: {
backgroundColor: '#f4511e', //Set Header color
},
headerTintColor: '#fff', //Set Header text color
headerTitleStyle: {
fontWeight: 'bold', //Set Header text style
},
}}
/>
<Stack.Screen
name="SecondPage"
component={SecondPage}
options={{
title: 'Second Page', //Set Header Title
headerStyle: {
backgroundColor: '#f4511e', //Set Header color
},
headerTintColor: '#fff', //Set Header text color
headerTitleStyle: {
fontWeight: 'bold', //Set Header text style
},
}}
/>
</Stack.Navigator>
</NavigationContainer>
);
};
export default App;
Open FirstPage.js in any code editor and replace the code with the following code.
FirstPage.js
// Refresh Previous Screen after Going Back in React Navigation
// https://aboutreact.com/refresh-previous-screen-react-navigation/
import React, {useEffect, useState} from 'react';
import {Button, View, Text, SafeAreaView} from 'react-native';
const FirstPage = ({navigation}) => {
const [count, setCount] = useState(0);
useEffect(() => {
// Interval to update count
const interval = setInterval(() => {
setCount((count) => count + 1);
}, 1000);
// Subscribe for the focus Listener
const unsubscribe = navigation.addListener('focus', () => {
setCount(0);
});
return () => {
// Clear setInterval in case of screen unmount
clearTimeout(interval);
// Unsubscribe for the focus Listener
unsubscribe;
};
}, [navigation]);
return (
<SafeAreaView style={{flex: 1}}>
<View style={{flex: 1, padding: 16}}>
<View
style={{
flex: 1,
alignItems: 'center',
justifyContent: 'center',
}}>
<Text
style={{
fontSize: 25,
textAlign: 'center',
marginBottom: 16,
}}>
This is the First Page of the app
</Text>
<Text style={{textAlign: 'center', paddingVertical: 10}}>
Counter will reset when you came back from Second Screen
</Text>
<Text>Count: {count}</Text>
<Button
title="Go to Second Sreen"
onPress={() => navigation.navigate('SecondPage')}
/>
</View>
<Text style={{textAlign: 'center', color: 'grey'}}>
www.aboutreact.com
</Text>
</View>
</SafeAreaView>
);
};
export default FirstPage;
Open SecondPage.js in any code editor and replace the code with the following code.
SecondPage.js
// Refresh Previous Screen after Going Back in React Navigation
// https://aboutreact.com/refresh-previous-screen-react-navigation/
import React from 'react';
import {View, Text, SafeAreaView} from 'react-native';
const SecondPage = () => {
return (
<SafeAreaView style={{flex: 1}}>
<View style={{flex: 1, padding: 16}}>
<View
style={{
flex: 1,
alignItems: 'center',
justifyContent: 'center',
}}>
<Text
style={{
fontSize: 25,
textAlign: 'center',
marginBottom: 16,
}}>
This is Second Page of the App
</Text>
</View>
<Text style={{textAlign: 'center', color: 'grey'}}>
www.aboutreact.com
</Text>
</View>
</SafeAreaView>
);
};
export default SecondPage;
To Run the React Native App
Open the terminal again and jump into your project using.
cd ProjectName
To run the project on an Android Virtual Device or on real debugging device
react-native run-android
or on the iOS Simulator by running (macOS only)
react-native run-ios
Output Screenshots
Without Refresh Event Listener (Without didFocus)
With Refresh Event Listener (With didFocus)
Output in Online Emulator
This is how you can Refresh the Previous Screen after Going Back in React Navigation. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!
Hope you liked it. 🙂
Man… You save my life again. Thank you so much. Works perfectly for me.
hi you can aslo use state params context to load Previous Screen When Going Back.
this.props.navigation.state.params.context.YOUR-FUNCTION-NAME-ON-PREVIOUS-SCREEN();
like
function(){
if(something == true){
this.props.navigation.state.params.context.function1(); // run function on pre screen
this.props.navigation.navigate(“Previous Screen”); // to go back
}
}
Thank you for sharing 🙂
Thanks for taking time to write up the article. it helped me. Appreciate your time. Thank you!
Estoy usando un didmount para cargar los datos de mysql(pantalla A) al ir a una pantalla B y actualizar esos datos. regreso a pantalla A pero esos datos no se actualizaron .ayuda
Hey hi, It does not refresh the whole screen. It just calls the function associated with the ‘didFocus’. If you see in this example I have used this.setState({ count: 0 }); to reset my state. So put all your code in a method and call the method from function associated with ‘didFocus’
i think better approach will be using react lifecycle method instead,
For ex:
componentDidUpdate(prevProps, prevState) {
if (this.props.route.params !== prevProps.route.params) {
this._onRefresh();
}
},
You can put all function you call on when page mount
Thanks for sharing with all
Your solve does not work, I got the same route name at back to the screen. These are equals this.props.route.params, prevProps.route.params also I tried this.props.navigation.state.routeName !== prevProps.navigation.state.routeName and does not work because I got the same route name, please could you post how you fix it.
FocusListner.remove() not found, it shows focusListner is not a function
Updated the post for the same