React Native force component refresh when the app goes to foreground

7.8k Views Asked by At

My app displays some Texts. I need to re-render a Component when the font size changes via Settings --> Accessibility --> Font size:

enter image description here

So basically this is se sequence:

  • The app is opened (foreground).
  • The user opens the Phone Settings so the app goes to foreground (not completely closed).
  • The user changes the Font size via via Settings --> Accessibility --> Font size.
  • The user closes the Settings and opens the app goes to foreground again.

At this point I need to reload the app because some Components need to be adapted.

I'm using react-native-device-info to get the font size using const fontScale = DeviceInfo.getFontScale(); but its value doesn't get updated until the app is completely closed and opened.

Any ideas?

1

There are 1 best solutions below

3
On BEST ANSWER

You can set the appstate to nextAppState. It should cause the component to rerender.

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.setState({appState: nextAppState});
  };

  render() {
    return <Text>Current state is: {this.state.appState}</Text>;
  }
}