Created
June 26, 2022 09:48
-
-
Save exuanbo/4e2827042e21023f28c0798ee286110a to your computer and use it in GitHub Desktop.
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
interface StateRefObject<T> { | |
readonly current: T | |
} | |
export const useStateWithRef = <T>( | |
initialValue: T | (() => T) | |
): [T, React.Dispatch<React.SetStateAction<T>>, StateRefObject<T>] => { | |
const [state, __setState] = useState(initialValue) | |
const stateRef = useRef(state) | |
const setState = useCallback((value: T | ((prevState: T) => T)) => { | |
__setState(value) | |
stateRef.current = isFunction(value) ? value(stateRef.current) : value | |
}, []) | |
return [state, setState, stateRef] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment