The following code fetches data but has a bug that can cause a memory leak. What is the primary cause of this bug?

React JS interview question for Advanced practice.

Answer

The useEffect hook is missing a cleanup function to handle the case where the component unmounts before the fetch completes.

Explanation

The bug is the lack of a cleanup function. If the component unmounts before the fetch promise resolves, the .then() callback will still execute and attempt to call setData on a component that is no longer mounted. This will result in a React warning: "Can't perform a React state update on an unmounted component" and is a memory leak. The fix is to return a cleanup function that cancels the request, for example using an AbortController.

Related Questions