I have a Code Sandbox (fork if you like) where I experimented with how Fast Refresh was working in that environment. I could see these weird effects when it came to the callbacks set to run in useEffect
:
- On remounting the root component it was not calling the cleanup function of useEffect. It would only be called before the next effect run.
- It actually never unmounted the previous version - keeping multiple root components, which is visible in the Components tab of React Dev Tools
- The
//@reset
directive only seems to reset the state on initial render. On subsequent renders (after changing the state of the last mounted root component), the state magically reappears
Example
Say, I have 3 App
components running (not by will, but by the aforementioned weirdness), they will all print their internal state on re-render. If they have these three states:
{counter: 5, id: 5234}
{counter: 1, id: 9187}
{counter: 9, id: 4582}
Then, if changing some comment in the App
component will trigger code sandbox to mount a new version of App
and the 4 instances will now print:
{counter: 0, id: 5234}
{counter: 0, id: 9187}
{counter: 0, id: 4582}
{counter: 0, id: 7294}
Then, if clicking the button to bump the counter the previous states magically reappears in the console:
{counter: 5, id: 5234}
{counter: 1, id: 9187}
{counter: 9, id: 4582}
{counter: 1, id: 7294}
So much for //@reset
being useful :D
Is this code sandbox specific behaviour for Fast Refresh or is it working like this everywhere? I tried exporting the sandbox, but when I ran the project locally, any change on App
would just reload the page, not use Fast Refresh, so I could not try it out for whatever reason.