Is it possible to retrieve the initial state after the state has changed? F.ex:
React.createClass({
getInitialState: function() {
return { foo: 'bar' }
},
componentWillMount: function() {
this.setState({ foo: 'foo' })
},
componentDidMount: function() {
// get the initial state "bar" ?
}
})
I couldn’t find anything in the docs. I could of course save the value in an external variable, but I was just curios if it was possible to treat the initialstate as a "config" object that could be re-used.
React components automatically re-render whenever there is a change in their state or props. A simple update of the state, from anywhere in the code, causes all the User Interface (UI) elements to be re-rendered automatically.
The componentDidMount() method is called after the component is rendered. This is where you run statements that requires that the component is already placed in the DOM.
State updates in React are asynchronous; when an update is requested, there is no guarantee that the updates will be made immediately. The updater functions enqueue changes to the component state, but React may delay the changes, updating several components in a single pass.
While there's currently no React Hook that does this out of the box, you can manually retrieve either the previous state or props from within a functional component by leveraging the useRef , useState , usePrevious , and useEffect Hooks in React.
No, the initial state isn't stored -- but you can call this.getInitialState()
if you want to reexecute the function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With