Last active
April 24, 2020 19:24
-
-
Save ushu/b59cd387745dbd499d42de81639c7b79 to your computer and use it in GitHub Desktop.
A(nother) version of setState that won't raise an error when called on an unmounted component, TypeScript version
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 { | |
useState, | |
Dispatch, | |
SetStateAction, | |
useRef, | |
useEffect, | |
useCallback, | |
} from "react" | |
function useSafeState<S = undefined>( | |
initialState: S | (() => S), | |
): [S | undefined, Dispatch<SetStateAction<S | undefined>>] { | |
const [state, setState] = useState<S | undefined>(initialState) | |
// detect unmount | |
const mounted = useRef(true) | |
useEffect( | |
() => () => { | |
mounted.current = false | |
}, | |
[mounted], | |
) | |
// and wrap setState to avoid calling it on unmounted components | |
const safeSetState: Dispatch<SetStateAction<S | undefined>> = useCallback( | |
(value: SetStateAction<S | undefined>) => { | |
if (mounted.current) setState(value) | |
}, | |
[mounted, setState], | |
) | |
return [state, safeSetState] | |
} | |
export default useSafeState |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment