A memory leak occurs when a computer program allocates memory but fails to release it after it’s no longer needed.

Signs

  • Performance degradation, gradual increase of memory usage over time
  • Server crashes
  • Unresponsiveness of applications

In React

In React, memory leaks typically happen when components are unmounted, but some of their resources like event listeners, timers, or subscriptions remain active.

Modern JavaScript engines use automatic garbage collection to reclaim memory from objects that are no longer in use. However, the garbage collector can only free memory that is unreachable. If objects are still referenced, such as when event listeners or timers remain active, the garbage collector will not release their memory, leading to a memory leak.

TIP

Use cleanup function to remove event listeners, subscriptions, etc. when using useEffect.

Sources