difference between componentDidMount and getInitialState in Reactjs

9.9k Views Asked by At

I understand that getInitialState is called once in the component's lifecycle and componentDidMount is called when the component is rendered.

So does that mean both will get called just once in the component's lifecycle? What's the difference?

1

There are 1 best solutions below

0
On BEST ANSWER

getInitialState is called at first instantiation of the component. It should always return an object and this object will be the initial state of this.state within the component. You don't have to define getInitialState if you don't want to, perhaps you don't need an internal state, in which case don't define it.

componentDidMount is called once the component is actually mounted to the DOM. But not, as you suggested, every time the component is rendered. If you're looking for something that runs every time the component is rendered (other than the render) take a look at componentWillUpdate and/or componentDidUpdate.

As for the main differences, getInitialState is quite literally just supposed to return the initial state for that component, nothing else. The function is executed long before the component is actually rendered to the DOM. componentDidMount is executed directly after the component has been rendered to the DOM, so for example you could now do things which require the component to be on the DOM first, such as using this.getDOMNode() to check the exact height of your component's root HTML element, or modifying it's scroll position.

You're right though, both will only be called once in the lifetime of an instance of your React component.