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:
27
web/src/utils/hooks/useStateWithCallback.ts
Normal file
27
web/src/utils/hooks/useStateWithCallback.ts
Normal 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
|
||||
Reference in New Issue
Block a user