I have a simple component
that maintains an internal state. I have another component
that toggles whether or not <
Hmm, you could use localStorage
, or AsyncStorage
if React Native.
React Web
componentWillUnmount() {
localStorage.setItem('someSavedState', JSON.stringify(this.state))
}
Then later that day or 2 seconds later:
componentWillMount() {
const rehydrate = JSON.parse(localStorage.getItem('someSavedState'))
this.setState(rehydrate)
}
React Native
import { AsyncStorage } from 'react-native'
async componentWillMount() {
try {
const result = await AsyncStorage.setItem('someSavedState', JSON.stringify(this.state))
return result
} catch (e) {
return null
}
}
Then later that day or 2 seconds later:
async componentWillMount() {
try {
const data = await AsyncStorage.getItem('someSavedState')
const rehydrate = JSON.parse(data)
return this.setState(rehydrate)
} catch (e) {
return null
}
}
You could also use Redux
and pass the data into the child component when it renders. You might benefit from researching serializing
state and the second parameter of the Redux createStore
function which is for rehydrating an initial state.
Just note that JSON.stringify()
is an expensive operation, so you should not do it on keypress, etc. If you have concern, investigate debouncing.