Hey everyone! I recently took over a project that isn't very large, but it seems quite unoptimized. It's almost crashing my M1 Air with 8GB of RAM when I start the local server. I noticed that there are nearly 500 uses of `useMemo` and `useCallback`, which I suspect might be contributing to the problem. The app is also using Create React App. So, my question is: what methods or tools can I use to identify which parts of the code are causing the most memory load? How should I tackle this issue?
3 Answers
First thing I'd recommend is getting the app off Create React App and switching to Vite. It'll make a big difference. Once that’s done, focus on the hooks.
High memory usage could come from several factors: Memory leaks (like `useEffect` without cleanup), overusing `useMemo` and `useCallback` which keep references alive, large global state stores like Redux, huge JavaScript bundles from libraries, large lists without virtualization, unbounded data caching, excessive re-renders, heavy dev mode in CRA, importing entire libraries instead of tree-shaken modules, and keeping data outside React's lifecycle. Addressing these issues can help reduce RAM consumption.
500 memo and callback hooks in a small app? Wow! Whoever wrote that code was definitely overdoing it. If your app is crashing on startup, it's probably due to Webpack choking during the build rather than an issue with the app logic. Try running `NODE_OPTIONS="--max-old-space-size=4096" npm start` to give Node more memory. It might help stop the crashes for now. But be prepared for a tedious refactor. You'll need to check why all those hooks are there. React can consume a lot of memory just tracking dependencies, so if those hooks are memoizing basic objects or calculations, they could actually be slowing things down instead of helping. Evaluate each one and remove any that aren't protecting complex computations.

Interesting to note that it was already running on `--max-old-space-size=5120` when I took over. So, is there any tool that can show which components are taking up memory? I'm starting to fear that I might have to check each hook manually.