Skip to content

Instantly share code, notes, and snippets.

@colus001
Last active August 29, 2019 09:22
Show Gist options
  • Save colus001/39244508418adbdae55637e4e4ccd601 to your computer and use it in GitHub Desktop.
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.`
/**
* 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];
}
@colus001
Copy link
Author

colus001 commented Aug 29, 2019

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment