How to Make the Screen Refresh when Navigating Back in React Native

Last Updated on December 10, 2020.

In this blog post, I show you how to make the screen refresh when you navigate back in react native using react navigation library. Most of the react native projects out there prefer react navigation library for the navigation solutions.

Usually, when a user navigates back using the back arrow of the header or hardware back button the screen where you are navigating will not refresh or update. By default, it is done for performance and optimization purposes.

What if you want to make some changes to the screen you are navigating back to? In such cases, you can use Navigation Events API from React Navigation. It has many built in events such as focus, blur, beforeRemove, state, etc. You can use the focus event so that the focussed screen will get refreshed.

Firstly, install the react navigation library to your react native project using the following command.

npm install @react-navigation/native

React navigation is dependent on some other libraries. So install them using the following command.

npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view

We will be using Stack Navigator to demonstrate the example. Hence install it using the following command.

npm install @react-navigation/stack

Now, you have to add the following line at the top of your entry file, that is index.js file.

import 'react-native-gesture-handler';

Now, the installation of react navigation is completed. If you have any doubts on installation then refer the official documentation.

You can easily refresh the screen on focus as given below.

React.useEffect(() => {
    const unsubscribe = navigation.addListener('focus', () => {
      console.log('Refreshed!');
    });
    return unsubscribe;
  }, [navigation]);

As you see, We used useEffect hook and the unsubscribe function can be returned as the cleanup function in the effect.

In the following example, I am using react navigation library to navigate from screen named Home to screen named Hample. I have added a listener using the useEffect hook in the Home screen. Inside it, there is an Alert function. The Alert function prompts when Home screen is focused as well as when navigating back from sample screen to the home screen.

App.js

import * as React from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack';
import Home from './Home';
import Sample from './Sample';

const Stack = createStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={Home} />
        <Stack.Screen name="Sample" component={Sample} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;

Home.js

import React from 'react';
import {StyleSheet, Button, Alert, View} from 'react-native';

const Home = ({navigation}) => {
  React.useEffect(() => {
    const unsubscribe = navigation.addListener('focus', () => {
      Alert.alert('Refreshed');
    });
    return unsubscribe;
  }, [navigation]);
  return (
    <View style={styles.container}>
      <Button
        onPress={() => {
          navigation.navigate('Sample');
        }}
        title="Learn More"
        color="#841584"
      />
    </View>
  );
};

export default Home;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#2c3e50',
  },
});

Sample.js

import React from 'react';
import {StyleSheet, Text, View} from 'react-native';

const Sample = () => {
  return (
    <View style={styles.container}>
      <Text>Go back to test</Text>
    </View>
  );
};

export default Sample;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
  },
});

If you are preferring class based components, then you can change Home.js file as given below.

import React, {Component} from 'react';
import {StyleSheet, Button, Alert, View} from 'react-native';

export default class Home extends Component {
  componentDidMount() {
    this._unsubscribe = this.props.navigation.addListener('focus', () => {
      Alert.alert('Refreshed');
    });
  }

  componentWillUnmount() {
    this._unsubscribe();
  }
  render() {
    return (
      <View style={styles.container}>
        <Button
          onPress={() => {
            this.props.navigation.navigate('Sample');
          }}
          title="Learn More"
          color="#841584"
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#2c3e50',
  },
});

Following is the output this react native example.

If you are a huge fan of React hooks then you may also check out the useFocusEffect hook from react navigation which do similar jobs.

This react native tutorial is demonstrated using react native version 0.63.4 and react navigation version 5.8.10. Please let me know your doubts and suggestions in the comment box.

3 thoughts on “How to Make the Screen Refresh when Navigating Back in React Native”

Leave a Reply

%d bloggers like this: