Skip to content

Please explain in the main concepts that react doesn't refire componentDidMount even with conditional rendering and the solution is to use different keys #2922

Description

@Zhell1

As said by someone else here: "This should be way more obvious in the React documentation. This achieved exactly what I was after, but took hours to find."

This also took me hours to find that react doesn't automatically re-mount a component if the code is similar but just props change.

I was using conditional rendering doing:

var mycode = ""
if(a==true) {
      mycode = <MyComponent myvar="true"/>
} else {
      mycode = <MyComponent myvar="false"/>
}

And was expecting componentDidMount to fire to do crucial stuff, which obviously doesn't happen unless you specify a different key for both (solution at the bottom).

Please make this part of the Main Concepts of the React doc. The above linked answer got +190 upvotes which shows that this is a real problem for many coders.

Thank you very much for your consideration

Solution:

var mycode = ""
if(a==true) {
      mycode = <MyComponent myvar="true" key="1"/>
} else {
      mycode = <MyComponent myvar="false" key="2"/>
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions