React Native

Memory Management

Memory leaks, cleanup, useEffect cleanup, listeners, timers, large images handling

20 câu hỏi phỏng vấn·
Senior
1

What is a memory leak in a React Native application?

Câu trả lời

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.

2

What is the role of the return function (cleanup function) in useEffect for memory management?

Câu trả lời

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.

3

Why is it important to use clearTimeout and clearInterval in the useEffect cleanup function?

Câu trả lời

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.

4

How to prevent memory leaks when using event listeners in React Native?

5

What is the impact of closures on memory management in React Native components?

+17 câu hỏi phỏng vấn

Nắm vững React Native cho lần phỏng vấn tiếp theo

Truy cập tất cả câu hỏi, flashcards, bài kiểm tra kỹ thuật, bài tập code review và mô phỏng phỏng vấn.

Bắt đầu miễn phí