reactjsreact-nativeexpo

How to have page re-rendered after exiting and re-opening the app?


This seems to be a dumb question, but I didn't find a one in SO.

Here is it:

I have a react native app. Every time I exit the app and re-open it, I expect to have Home page as the default screen being displayed, and also re-render the Home page as componentDidMount inside the Home screen will fetch latest data from the database. How can we achieve such case? Thanks!


Solution

  • If you don't mean closing the app and rather just sending it to the background, you can use the exported AppState object to detect it. See the answer to this question for an example. Once you detect the event, you can force a rerender using forceUpdate() for class components, or by using a dummy hook in functional components

    Slightly modified React docs example:

    import React, {Component} from 'react';
    import {AppState, Text} from 'react-native';
    
    class AppStateExample extends Component {
      state = {
        appState: AppState.currentState,
      };
    
      componentDidMount() {
        AppState.addEventListener('change', this._handleAppStateChange);
      }
    
      componentWillUnmount() {
        AppState.removeEventListener('change', this._handleAppStateChange);
      }
    
      _handleAppStateChange = (nextAppState) => {
        if (
          this.state.appState.match(/inactive|background/) &&
          nextAppState === 'active'
        ) {
          console.log('App has come to the foreground!');
          this.forceUpdate();
        }
        this.setState({appState: nextAppState});
      };
    
      render() {
        return <Text>Current state is: {this.state.appState}</Text>;
      }
    }
    

    Functional component (untested):

    import React, { useState, useEffect } from 'react';
    import { AppState } from 'react-native';
    
    const App = () => {
      const [updateVal, setUpdateVal] = useState(false);
      const forceUpdate = newState => {
        if (newState === 'active')
          setUpdateVal(!updateVal); // forces a rerender
      }
      useEffect(() => {
        AppState.addEventListener('change', forceUpdate);
        return () => AppState.removeEventListener('change', forceUpdate);
      }, []);
      // return your contents
    };
    

    However, if you're actually closing it (not just leaving the app), it should rerender.