Advertisement
Guest User

Untitled

a guest
Apr 21st, 2019
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.64 KB | None | 0 0
  1. import * as React from 'react';
  2.  
  3. /**
  4. * extend the React.useState to have the state referente, so it will be possible to use its value
  5. * inside of other callbacks
  6. *
  7. * @param {T} initialValue
  8. *
  9. * @return {[T, React.MutableRefObject<T>, React.Dispatch<React.SetStateAction<T>>]} array
  10. */
  11. export function useRefState<T>(
  12. initialValue: T
  13. ): [T, React.MutableRefObject<T>, React.Dispatch<React.SetStateAction<T>>] {
  14. const [state, setState] = React.useState<T>(initialValue);
  15. const stateRef = React.useRef<T>(state);
  16. React.useEffect(() => {
  17. stateRef.current = state;
  18. }, [state]);
  19. return [state, stateRef, setState];
  20. }
  21.  
  22. export default useRefState;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement