Skip to content

Instantly share code, notes, and snippets.

@exuanbo
Created June 26, 2022 09:48
Show Gist options
  • Save exuanbo/4e2827042e21023f28c0798ee286110a to your computer and use it in GitHub Desktop.
Save exuanbo/4e2827042e21023f28c0798ee286110a to your computer and use it in GitHub Desktop.
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