trunghv-use-state-with-call-back
Version:
��# t r u n g h v - u s e - s t a t e - w i t h - c a l l - b a c k
22 lines (17 loc) • 605 B
JavaScript
import { useState, useRef, useEffect } from 'react';
function useStateWithCallback(initState) {
const callbackRef = useRef(null)
const [state, setState] = useState(initState)
useEffect(() => {
if (callbackRef.current) {
callbackRef.current(state)
callbackRef.current = null
}
}, [state])
const setCallbackState = (value, callback) => {
callbackRef.current = typeof callback === 'function' ? callback : null
setState(value)
}
return [state, setCallbackState]
}
export default useStateWithCallback