Difference between componentDidMount and getInitialState in Reactjs

I understand that getInitialState is called once in the lifecycle of a component, and the componentDidMount is called when the component is rendered.

Does this mean that both will be called once in the component lifecycle? Who cares?

+3


source to share


1 answer


getInitialState

called the first time the component is instantiated. It should always return an object, and that object will be the initial state this.state

inside the component. You don't need to define getInitialState

if you don't want to, maybe you don't need internal state, in which case don't define it.

componentDidMount

called after the component is actually set to the DOM. But no, as you said, every time the component is rendered. If you're looking for something that gets executed every time a component is displayed (other than render

) take a look at componentWillUpdate and / or componentDidUpdate .



As far as the main differences getInitialState

go , it should quite literally return the original state for this component, nothing else. The function is executed long before the component is actually passed to the DOM. componentDidMount

is executed immediately after the component has been passed to the DOM, so for example you can now perform actions that require the component to be in the DOM first, such as using this.getDOMNode()

an HTML element to check the exact height of your component root or changing it scrolling.

You are correct, although both of them will only be called once in the lifetime of your React component instance.

+17


source







All Articles