From 83d819df53f3b7e2b6a8940b1273f766c26e875d Mon Sep 17 00:00:00 2001 From: Sabir Hassan Date: Tue, 26 Jul 2022 23:12:55 +0500 Subject: [PATCH] chore(web): created custom useStateWithCallback hook --- web/src/utils/hooks/useStateWithCallback.ts | 27 +++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 web/src/utils/hooks/useStateWithCallback.ts 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