Please explain in the main concepts that react doesn't refire componentDidMount even with conditional rendering and the solution is to use different keys
Nobody has claimed this yet.
- Dominant language
- JavaScript
- Stars
- 11.8k
- Forks
- 7.9k
- Avg merge
- 1d 11h
- Merged PRs (30d)
- 11
Description
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"/>
}
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start in the React documentation's Main Concepts section, which the issue identifies as the intended entry point. Explain that conditional rendering with changed props does not remount the same component, and document the distinct-key approach shown in the issue; done means the behavior and solution are clear to readers.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, react
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100