With introduction of fat arrow functions ➕ the implicit bind magic, JS developers found an everlasting 💛 towards them.
Although they were eye pleasing and a delight, they bought with a variety of concerns if not implemented wisely.
One such case i found myself having numerous conversations with my peers about; is having anonymous functions to handle the events which developers find easy to use and miss the subtle ugly memory leak they cause.
P.S This article won't be dwelling to the 🐘 depths of memory leak identification and resolutions but to emphasis on the fact that taking the easy route in this case will end up hitting the hardest.
An anonymous function might not be cleared by GC (garbage collection) efficiently during a mark and sweep phase as the references to it cannot be determined hence GC fails to recover back the allocated memory
- Production react build running on chrome
- Run about 10k state changes on each scenario of with and without anonymous implementation to trigger re-renders
That being said, let's jump on to the crux and look at some stats;
Recording a snapshot of each implementation clearly depicts a memory leak with the anonymous function implementation
Snapshot without anonymous functions
🔸 fig (i)
Snapshot with anonymous functions
🔸 fig (ii)
As we compare fig (i) with fig (ii) it's clear that the memory allocation has been freed up by GC in fig (i) as opposed to that of fig(ii)
The exaggerated example intends to portrays the memory leak with the approach; which holds true for apps of multiple complexities in the real world
Anonymous fat arrow functions within render methods pave way for a memory leak and ipso facto an anti-pattern
If you have questions, let us know in the comments and we are looking forward for your feedback 🍻