React Native - Whats the best way to remount / reset / reload a screen?
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>
)
}
}