Last active
August 29, 2019 09:22
-
-
Save colus001/39244508418adbdae55637e4e4ccd601 to your computer and use it in GitHub Desktop.
Avoid memory leak when using React useState API with async function. Fix `Warning: Can't perform a React state update on an unmounted component.`
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
/** | |
* useSafeState | |
* - To avoid memory leak when setState called after unmounted | |
* @param defaultValue | |
*/ | |
export function useSafeState<T>(defaultValue?: T): [T, React.Dispatch<React.SetStateAction<T>>] { | |
let isMounted = true; | |
React.useEffect(() => () => { | |
isMounted = false; | |
}, []); | |
const [state, setState] = React.useState<T>(defaultValue as T); | |
const safelySetState = (x: React.SetStateAction<T>) => { | |
if (!isMounted) return; | |
setState(x); | |
}; | |
return [state, safelySetState]; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Since React.useState doesn't care component's mounted state, useSafeState can be helpful to avoid memory leak.
Related issue: facebook/react#14369
Warning: Can't perform a React state update on an unmounted component.