Created
February 20, 2022 09:12
-
-
Save buglessir/773c8f3d20a6b42ec6b2e65444872935 to your computer and use it in GitHub Desktop.
3 ways to fix Memory Leaks in React web application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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