I've just had a look at this discussion about setState()
inside componentDidMount()
.
You can see that after the
render()
function, thecomponentDidMount()
function will be called by React. When you put asetState()
call incomponentDidMount()
then you are causing the entire component tree be re-rendered not only the current component - not to forget, the current component did just finished with rendering.
And some people suggested to put setState()
call inside componentWillMount()
. In some cases, I want to get the height of a rendered element and store it as state, and the above method wouldn't work. I also had a look at the React official website, and it suggests to do Ajax call inside componentDidMount()
, which again goes against the above idea.
So, am I wrong about putting setState()
inside componentDidMount()
? If yes, what should I apply as an alternative?
You may call
setState()
immediately incomponentDidMount()
. It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though therender()
will be called twice in this case, the user won’t see the intermediate state. Use this pattern with caution because it often causes performance issues. In most cases, you should be able to assign the initial state in theconstructor()
instead. It can, however, be necessary for cases like modals and tooltips when you need to measure a DOM node before rendering something that depends on its size or position.
React docs
Using DidMount makes it clear that data won’t be loaded until after the initial render. This reminds you to set up initial state properly, so you don’t end up with undefined state that causes errors.
Example
TLDR:
- If you have all needed data in constructor - assign state
there
constructor(props) {
super(props);
// Don't call this.setState() here!
this.state = { counter: 0 };
}
componentDidMount()
Your case with unknowing the height of a rendered element might be a valid excuse to use setState
inside componentDidMount
. However in such a case I would definitely add another lifecycle method,shouldComponentUpdate
, to control the rerender issue.
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