-
Notifications
You must be signed in to change notification settings - Fork 50
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
2c80499
commit cde740d
Showing
4 changed files
with
42 additions
and
6 deletions.
There are no files selected for viewing
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
import { useCallback, useState } from 'react'; | ||
import type { Dispatch, SetStateAction } from 'react'; | ||
import useUnmountedRef from './useUnmountedRef'; | ||
|
||
function useSafeState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>]; | ||
|
||
function useSafeState<S = undefined>(): [S | undefined, Dispatch<SetStateAction<S | undefined>>]; | ||
|
||
function useSafeState<S>(initialState?: S | (() => S)) { | ||
const unmountedRef = useUnmountedRef(); | ||
const [state, setState] = useState(initialState); | ||
const setCurrentState = useCallback((currentState) => { | ||
/** if component is unmounted, stop update */ | ||
if (unmountedRef.current) return; | ||
setState(currentState); | ||
}, []); | ||
|
||
return [state, setCurrentState] as const; | ||
} | ||
|
||
export default useSafeState; |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
import { useEffect, useRef } from 'react'; | ||
|
||
const useUnmountedRef = () => { | ||
const unmountedRef = useRef(false); | ||
useEffect(() => { | ||
unmountedRef.current = false; | ||
return () => { | ||
unmountedRef.current = true; | ||
}; | ||
}, []); | ||
return unmountedRef; | ||
}; | ||
|
||
export default useUnmountedRef; |