Skip to content

Instantly share code, notes, and snippets.

@bedekelly
Created July 19, 2021 09:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bedekelly/667ad970689cf9b983f0d971e9746407 to your computer and use it in GitHub Desktop.
Save bedekelly/667ad970689cf9b983f0d971e9746407 to your computer and use it in GitHub Desktop.
Use state hook with an extra "getState" parameter
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;
}
@bedekelly
Copy link
Author

bedekelly commented Jul 19, 2021

Use: const [count, setCount, getCount] = useStateWithCallback(0)

Then to access current state in a callback:

const currentCount = await getCount();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment