import { useCallback, useEffect, useRef, useState } from 'react' interface Callback { (state: S): void } export function useCallbackState( initialState: S | (() => S) ): [S, (nextState: S, cb?: Callback) => void] { const [state, setState] = useState(initialState) const callback = useRef>() const setCallbackState = useCallback((nextState: S, cb?: Callback) => { setState((prevState) => { callback.current = cb return typeof nextState === 'function' ? nextState(prevState) : nextState }) }, []) useEffect(() => { if (typeof callback.current === 'function') { callback.current(state) } }, [state]) return [state, setCallbackState] }