Memory Management
Memory leaks, cleanup, useEffect cleanup, listeners, timers, large images handling
1What is a memory leak in a React Native application?
What is a memory leak in a React Native application?
답변
A memory leak occurs when objects in memory are no longer used by the application but cannot be freed by the garbage collector because references to these objects still exist. In React Native, this commonly happens with uncleaned subscriptions, timers still active after unmount, or closures capturing stale references. Memory leaks gradually degrade performance and can cause crashes during long sessions.
2What is the role of the return function (cleanup function) in useEffect for memory management?
What is the role of the return function (cleanup function) in useEffect for memory management?
답변
The cleanup function returned by useEffect is executed before the component is unmounted or before the effect is re-executed with new dependencies. Its main role is to clean up resources allocated by the effect: cancel subscriptions, clearTimeout/clearInterval, remove event listeners, or abort pending requests. Without this cleanup, these resources continue to exist in memory and may attempt to update an unmounted component.
3Why is it important to use clearTimeout and clearInterval in the useEffect cleanup function?
Why is it important to use clearTimeout and clearInterval in the useEffect cleanup function?
답변
Timers created with setTimeout and setInterval continue to execute even after the component unmounts. If the timer callback attempts to update the state of an unmounted component, it triggers the warning 'Can't perform a React state update on an unmounted component' and constitutes a memory leak. The timer keeps a reference to the callback and its closure, preventing the garbage collector from freeing these resources. Using clearTimeout/clearInterval in cleanup ensures proper cancellation of these timers.
How to prevent memory leaks when using event listeners in React Native?
What is the impact of closures on memory management in React Native components?
+17 면접 질문