useStateWithGetter.ts 414 B

12345678910111213
  1. import { useRef, useState } from 'react';
  2. // https://github.com/facebook/react/issues/14543
  3. export default function useStateWithGetter(initial?: any) {
  4. const ref = useRef();
  5. const [state, setState] = useState(initial);
  6. ref.current = state;
  7. const set = (value: any) => {
  8. ref.current = value;
  9. setState(value);
  10. };
  11. const get = () => ref.current;
  12. return [state, set, get];
  13. }