I kept getting the Warning: Can't perform a React state update on an unmounted component message on a number of pages I was working on that are written using TypeScript with React. I'd seen a number of forums offering a solution that includes setting a state variable called _isMounted and setting it to true before running any initializing functions. I had done that and kept getting the error but after some experimentation found a solution that works, although I don't know why it works.
This was my first approach. The warning message still displayed with this code in place
const [_isMounted, set_isMounted] = useState<boolean>(false);
useEffect((): () => void => {
window.addEventListener('resize', updateWindowDimensions);
updateWindowDimensions();
set_isMounted(true);
return (): void => {
window.removeEventListener('resize', updateWindowDimensions);
}
}, []);
useEffect((): void => {
if (_isMounted === true) {
function1();
function2();
function3();
function4();
function5();
}
}, [_isMounted]);
Changing it up by initialziing _isMounted as undefined, setting it to false, and then setting it to true seems to have solved the issue
const [_isMounted, set_isMounted] = useState<boolean>();
useEffect((): () => void => {
window.addEventListener('resize', updateWindowDimensions);
updateWindowDimensions();
set_isMounted(false);
return (): void => {
window.removeEventListener('resize', updateWindowDimensions);
}
}, []);
useEffect((): void => {
if (_isMounted === false) {
set_isMounted(true);
}
}, [_isMounted]);
useEffect((): void => {
if (_isMounted === true) {
function1();
function2();
function3();
function4();
function5();
}
}, [_isMounted]);
Why would the first approach fail to resolve the issue while the second one succeeded?