Skip to content

Instantly share code, notes, and snippets.

@erkobridee
Last active April 11, 2019 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erkobridee/d1202079d23c9531c7b94f2138095b77 to your computer and use it in GitHub Desktop.
Save erkobridee/d1202079d23c9531c7b94f2138095b77 to your computer and use it in GitHub Desktop.
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