Last active
September 6, 2023 23:41
-
-
Save fatlinesofcode/a84710c462522430b7aca483dc546cab to your computer and use it in GitHub Desktop.
custom useState hook to return a promise for setState which resolves when the state changes
This file contains hidden or 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 { useEffect, useRef, useState } from 'react' | |
/** | |
* return a promise that resolves when useState updates | |
* | |
* @usage | |
* | |
* * const [state, setState] = useAwaitState('') | |
* | |
* * await setState('newVal') | |
* * doStuffAfterRenderStateChange() | |
* | |
* @param initialState | |
*/ | |
const useAwaitState = (initialState: any): [any, (newValue: any) => Promise<any>] => { | |
const [state, setState] = useState(initialState) | |
const callbackRef = useRef<Function>(null) | |
const setStateWithPromise = (newValue: any): Promise<any> => | |
new Promise((resolve, reject) => { | |
callbackRef.current = () => { | |
callbackRef.current = null | |
resolve(newValue) | |
} | |
setState(newValue) | |
}) | |
useEffect(() => { | |
if (callbackRef.current) { | |
callbackRef.current() | |
} | |
}, [state]) | |
useEffect( | |
() => () => { | |
// unmount hook | |
callbackRef.current = null | |
}, | |
[] | |
) | |
return [state, setStateWithPromise] | |
} | |
export default useAwaitState |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment