Is setState() inside componentDidMount() considered an anti-pattern

Normally you don't want to do synchronous state setting inside componentDidMount, you should just put it in the constructor. However element height is a bit unique, since you can't actually get the height of an element until it's mounted and rendered into the DOM.

So normally not, but in the case of element height it's ok to do it in 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.


You may call setState() immediately in componentDidMount(). It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the render() 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 the constructor() 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 };
}
  • Call async action, touch DOM in componentDidMount()

Tags:

Reactjs