Skip to content

Instantly share code, notes, and snippets.

@buglessir
Created February 20, 2022 09:12
Show Gist options
  • Save buglessir/773c8f3d20a6b42ec6b2e65444872935 to your computer and use it in GitHub Desktop.
Save buglessir/773c8f3d20a6b42ec6b2e65444872935 to your computer and use it in GitHub Desktop.
3 ways to fix Memory Leaks in React web application
// 1) Using Boolean flag:
const [value, setValue] = useState('');
useEffect(() => {
let isMounted = true;
fetchValue().then(() => {
if (isMounted) {
setValue('done!'); // no more error
}
});
return () => {
isMounted = false;
};
}, []);
// 2) Using AbortController:
useEffect(() => {
let abortController = new AbortController();
// your async action is here
return () => {
abortController.abort();
}
}, []);
// 3) Using use-state-if-mounted Hook:
// ### Download it here: https://www.npmjs.com/package/use-state-if-mounted
const [value, setValue] = useStateIfMounted('checking value...');
useEffect(() => {
fetchValue().then(() => {
setValue("done!"); // no more error
});
}, []);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment