diff --git a/web/src/utils/hooks/useStateWithCallback.ts b/web/src/utils/hooks/useStateWithCallback.ts new file mode 100644 index 0000000..f6acb92 --- /dev/null +++ b/web/src/utils/hooks/useStateWithCallback.ts @@ -0,0 +1,27 @@ +import { useState, useEffect, useRef } from 'react' + +export const useStateWithCallback = ( + initialValue: T +): [T, (newValue: T, callback?: () => void) => void] => { + const callbackRef = useRef(null) + + const [value, setValue] = useState(initialValue) + + useEffect(() => { + if (typeof callbackRef.current === 'function') { + callbackRef.current() + + callbackRef.current = null + } + }, [value]) + + const setValueWithCallback = (newValue: T, callback?: () => void) => { + callbackRef.current = callback + + setValue(newValue) + } + + return [value, setValueWithCallback] +} + +export default useStateWithCallback