Created
July 19, 2021 09:17
-
-
Save bedekelly/667ad970689cf9b983f0d971e9746407 to your computer and use it in GitHub Desktop.
Use state hook with an extra "getState" parameter
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
export function useStateWithCallback<T>( | |
defaultState: T | (() => T) | |
): readonly [T, Dispatch<SetStateAction<T>>, () => Promise<T>] { | |
const [state, setState] = useState<T>(defaultState); | |
const getState = useCallback(() => { | |
return new Promise<T>((resolve) => { | |
setState((oldValue) => { | |
resolve(oldValue); | |
return oldValue; | |
}); | |
}); | |
}, []); | |
return [state, setState, getState] as const; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use:
const [count, setCount, getCount] = useStateWithCallback(0)
Then to access current state in a callback: