1
0
mirror of https://github.com/sasjs/server.git synced 2025-12-10 11:24:35 +00:00

chore(web): created custom useStateWithCallback hook

This commit is contained in:
2022-07-26 23:12:55 +05:00
parent 95df2b21d6
commit 83d819df53

View File

@@ -0,0 +1,27 @@
import { useState, useEffect, useRef } from 'react'
export const useStateWithCallback = <T>(
initialValue: T
): [T, (newValue: T, callback?: () => void) => void] => {
const callbackRef = useRef<any>(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