Skip to content

Instantly share code, notes, and snippets.

@ushu
Last active April 24, 2020 19:24
Show Gist options
  • Save ushu/b59cd387745dbd499d42de81639c7b79 to your computer and use it in GitHub Desktop.
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
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