Last active
June 21, 2021 11:25
-
-
Save amerllica/985504bc41edf70d0a01c9b40e4c80c0 to your computer and use it in GitHub Desktop.
ReactJS hook for passing state and a setter function with ability of getting callback for each setter call.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useRef, useCallback, useEffect, useState } from 'react'; | |
import type { Dispatch, SetStateAction } from 'react'; | |
type StateFunctionType<S> = Dispatch<SetStateAction<S | undefined>>; | |
type SetStateCallbackGeneric<S> = ( | |
x: S | StateFunctionType<S>, | |
cb?: Function | |
) => void; | |
const useStateCallback = <T>( | |
initialState: T | |
): [T, SetStateCallbackGeneric<T>] => { | |
const [state, setState] = useState<T>(initialState); | |
const cbRef = useRef(null); | |
const setStateCallback = useCallback((newState, cb) => { | |
cbRef.current = cb; | |
setState(newState); | |
}, []); | |
useEffect(() => { | |
if (typeof cbRef?.current === 'function') { | |
cbRef?.current?.(state); | |
cbRef.current = null; | |
} | |
}, [state]); | |
return [state, setStateCallback]; | |
}; | |
export default useStateCallback; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment