Last active
April 11, 2019 08:41
-
-
Save erkobridee/d1202079d23c9531c7b94f2138095b77 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 * as React from 'react'; | |
/** | |
* extend the React.useState to have the state referente, so it will be possible to use its value | |
* inside of other callbacks | |
* | |
* @param {T} initialValue | |
* | |
* @return {[T, React.MutableRefObject<T>, React.Dispatch<React.SetStateAction<T>>]} array | |
*/ | |
export function useRefState<T>( | |
initialValue: T | |
): [T, React.MutableRefObject<T>, React.Dispatch<React.SetStateAction<T>>] { | |
const [state, setState] = React.useState<T>(initialValue); | |
const stateRef = React.useRef<T>(state); | |
React.useEffect(() => { | |
stateRef.current = state; | |
}, [state]); | |
return [state, stateRef, setState]; | |
} | |
export default useRefState; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment