import { useRef , useLayoutEffect , useState , useCallback } from 'react' ; const useSafeState = < S > ( initState ) => { const [ state , unsafeSetState ] = useState < S > ( initState ) ; const isMounted = useRef ( false ) ; useLayoutEffect ( ( ) => { isMounted . current = true ; return ( ) => { isMounted . current = false ; } ; } ) ; const setState = useCallback ( newState => { if ( isMounted . current ) { unsafeSetState ( newState ) ; } } , [ ] ) ; return [ state , setState ] ; } ; export default useSafeState as typeof useState ;