React Native - Whats the best way to remount / reset / reload a screen?

Raheel Hasan picture Raheel Hasan · Feb 8, 2018 · Viewed 25.2k times · Source

In React-Native, is there a way (or ways) to remount or reload the whole screen?

Im building a calculator, and if I follow this: https://facebook.github.io/react-native/docs/refreshcontrol.html

It still doesnt resets the input fields. Sure, I can write a code to reset every field on the screen, but is there a generic way to just refresh the screen?

For example, using the navigator if I just go to another screen and come back to this screen the data is gone from the fields and its all 0.0 again. How to achive that?

Here is the component's first node, everything is inside this

<ScrollView refreshControl={<RefreshControl
refreshing={this.state.refreshing} onRefresh={this.refreshMe.bind(this)} />}
>
.
.
.
.
.
.
</ScrollView>

Thanks

Answer

jevakallio picture jevakallio · Feb 8, 2018

An often-used hack in React is to change the key prop of your component to force a re-mount of a view:

class Thing extends React.Component {
  state = {
    uniqueValue: 1
  }
  forceRemount = () => {
    this.setState(({ uniqueValue }) => ({
      uniqueValue: uniqueValue + 1
    });
  }
  render() {
    return (
      <View key={this.state.uniqueValue}>
        <Button onPress={this.forceRemount} />
      </View>
    )
  }
}

React uses element keys to track elements to update, and if the key is changed, React will conclude that the previous element no longer exists, so it will be removed and the "new" element created.

That said, this would only work if the state you want to clear is stored in a stateful component within the child component tree (e.g. an uncontrolled TextInput that does not have its value prop set).

A cleaner solution is to make all your child components controlled so that your component's UI is a pure function of it's props and state, and simply reset the component state:

const initialState = {
  //...
}

class Thing extends React.Component {
  state = initialState;
  resetState = () => {
    this.setState(initialState);
  }
  render() {
    return (
      <View}>
        <Button onPress={this.resetState} />
      </View>
    )
  }
}