How to cancel a fetch on componentWillUnmount?

Posted by Jessica Taylor | Updated on

If you want to cancel a fetch on componentWillUnmount? When you fire a Promise it might take a few seconds before it resolves and by that time user might have navigated to another place in your app. So when Promise resolves setState is executed on unmounted component and you get an error – just like in your case. This may also cause memory leaks.

Alternatively with useRef which behaves like a static property of a class which means it doesn’t make component rerender when it’s value changes:

If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@] Your question and answer will appear on and help other developers.

Related Questions & Answers