Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix(react-refresh-utils): avoid memory leaks caused by prevExports (#…
…53797) This fixes memory leaks caused by `prevExports` in react-refresh-utils. It happens in code like the following: ```tsx const DATA = Array.from({ length: 100000 }, (_, i) => Math.random()); export const App = () => { return ( <div> <div>REWRITE_HERE</div> <div>{DATA.length}</div> </div> ); }; ``` After we edit this file to trigger fast refresh, previous `DATA` will be still retained in the memory since it forms `App(new) -> prevExports -> App(old) -> DATA` reference chain (there is some screenshots [here](pmmmwh/react-refresh-webpack-plugin#766)). I believe there is no reason to retain the whole exports as `prevExports`. We can just retain "signature" (`string[]`). By only holding this, we no longer create reference to the old exports, which fixes the memory leak here. Note that I filed a similar PR in pmmmwh/react-refresh-webpack-plugin#766 and also https://github.com/naruaway-sandbox/fast-refresh-hmr-memory-leak-demo is a reproducible example of this issue, which also explains that interestingly this issue is not easily solved for Vite. ## Should we fix it? I think yes, as long as there is no unintended side effect, it's better to fix it since we cannot predict whether users would load large payload AND does Fast Refresh many times without reloading the browser or not. In [this extreme case](https://github.com/naruaway-sandbox/fast-refresh-hmr-memory-leak-demo), it eats several hundred mega bytes of RAM. ## Verification I confirmed that the memory leak is gone with this change by running https://github.com/naruaway-sandbox/fast-refresh-hmr-memory-leak-demo with the change. I am not sure whether new tests are needed but my concern is to accidentally break Fast Refresh behavior somehow. I believe we have enough existing test cases 🙏 and I also tested manually.
- Loading branch information