componentDidMount() not being called when react component is mounted componentDidMount() not being called when react component is mounted reactjs reactjs

componentDidMount() not being called when react component is mounted


The issue here is that the render method is crashing, because the following line is generating an error

<p>{this.state.obj.allStarships.edges[1].node.name}</p>

Fix this to not use this.state.obj.allStarships.edges[1].node.name directly, unless you can guarantee that each receiver is defined.


Check your component's key

Another thing that will cause this to happen is if your component does not have a key. In React, the key property is used to determine whether a change is just new properties for a component or if the change is a new component.

React will only unmount the old component and mount a new one if the key changed. If you're seeing cases where componentDidMount() is not being called, make sure your component has a unique key.

With the key set, React will interpret them as different components and handle unmounting and mounting.

Example Without a Key:

<SomeComponent prop1={foo} />

Example with a Key

const key = foo.getUniqueId()<SomeComponent key={key} prop1={foo} />


Also check that you don't have more than one componentDidMount if you have a component with a lot of code. It's a good idea to keep lifecycle methods near the top after the constructor.