-
-
Save troygoode/0702ebabcf3875793feffe9b65da651a to your computer and use it in GitHub Desktop.
Hook for react state which prevents updates on unmounted components (in TypeScript)
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
import { useEffect, useRef, useState, Dispatch, SetStateAction } from "react"; | |
/* originally via: | |
https://gist.github.com/AlpacaGoesCrazy/25e3a15fcd4e57fb8ccd408d488554d7 | |
*/ | |
const useStateSafe = function<T>(initialValue: T): [T, Dispatch<SetStateAction<T>>] { | |
const isMounted = useRef(false); // useRef to memorize if the component is mounted between renders | |
const [state, setState] = useState<T>(initialValue); | |
useEffect(() => { | |
isMounted.current = true; | |
return () => { | |
isMounted.current = false; | |
}; | |
}); | |
const setStateSafe = (t: T | ((prev: T) => T)) => { | |
if (isMounted.current) { | |
// do not call setState if the component already unmounted | |
setState(t); | |
} | |
}; | |
return [state, setStateSafe]; | |
}; | |
export default useStateSafe; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi! Thank you for the great gist above! Do you know if this hook actually fixes the memory leak mentioned in the warning generated by React? Or does it just make sure no (no longer needed) state is updated and no warning is shown?