A component instance is installed only once and is unmounted when it is removed. In your case, it is deleted and recreated.
The key prop point is to help you find a previous version of the same component. Thus, he can update the previous component with the help of new details, and not create a new one.
The reaction can often work fine without a key, the exception is a list with items. He wants a key so that he can track when items are reordered, created, or deleted.
In your case, you explicitly tell React that your component is different from the previous one. You give a new key for each rendering. This causes React to treat the previous instance as remote. Any children of this component are also dismounted and dismantled.
What you have to do is (never) generate a key at random. Keys should always be based on the identity of the data displayed by the component. If it's not a list item, you probably don't need a key. If this is a list item, it is much better to use a key obtained from a data identifier, for example, an ID property or, possibly, a combination of several fields.
If generating a random key would be the right thing, React just took care of this for you.
You must put your sample source code in the root of the React tree, usually this is the App . Do not place it on a random child. At the very least, you should put it in a component that exists for the life of your application.
The main reason to put it in componentDidMount is because it does not start on the server, because server components are never mounted. This is important for universal rendering. Even if you do not do it now, you can do it later, and preparing for it is best practice.