Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: Get initialstate after state has changed

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.

like image 231
David Hellsing Avatar asked Jul 09 '14 07:07

David Hellsing


People also ask

Does React re-render if state changes?

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.

Is componentDidMount called after state change?

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.

What happens when state is updated in React?

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.

How do I get past state in React hooks?

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.


1 Answers

No, the initial state isn't stored -- but you can call this.getInitialState() if you want to reexecute the function.

like image 86
Sophie Alpert Avatar answered Sep 28 '22 09:09

Sophie Alpert