React Hook Memory Leak Fix

April 07, 2023

Share:
Tag(s):

While studying the syllabus for the ISTQB Advance Level TTA certificate, I revisited the static and dynamic analysis for memory leaks. Hence, I tried to practise the methods by analyzing and improving the performance this web blog.

I tried to monitor the memory performances of different pages of this website.

Memory Monitoring

The Shallow Size and Retained Size are quite small in average for all pages. The only 2 outstanding pages are the homepage and the Blog page, where the UseEffect hooks are used.

It makes sense because the code inside UseEffect runs on every render so it could provide functionalities like DOM update, and data fetching in client side.

I did a little bit google to learn the best practice and found this useful article How To Fix Memory Leak Issue In React Js Using Hook.

And then I added the AbortController to the hooks I used in the 2 pages. There is a significant memory usage drop for the homepage:

Before the fix:

Memory Usage Before Fix

After the fix:

Memory Usage After Fix

The result looks awesome with this little trick. Eventhough it is certain that this little small optimization would never be a matter for this website, system performance caused by memory leaks would be an issue for those safety critical software in aerospacing, automotive and medical technology. Many modern frameworks include good-to-go garbage collection designs by default but still, code speaks for itself.

via GIPHY


Recommended Reading:

What is Memory Leak? How can we avoid?

ISTQB Glossary - Memory Leak