Search code examples
reactjslifecycle

componentWillUnmount not getting called un less all instances of a same component are removed from display. is it expected?


When we have multiple instances of same react component created, componentWillUnmount is not getting called unless all the instances are removed from display. Is it expected ?


Solution

  • I found the issue. In my case we have a container which displays components based on the contents of an array.

    The index from the array is used as a key to the component. The elements in the array are altered based on network communication.

    So initially a component is created of a certain type with key as 0. When we receive communication from network we remove the above said type from the array and add a new type.

    When the render is invoked the component is re-created but with new type and key being the same 0.

    As the key is same 0 for the previous and newly created component the componentDidMount and componentWillUnmount methods are not being invoked.

    Once i've changed the key from index to the type of the component the issues was resolved. Might help anyone in the future with similar kind of issue.

    Thanks