Last updated on

React 中的闭包问题

const useStateWithRef = initialVal => {
  const [state, setState] = useState(initialVal);
  const ref = useRef(initialVal);
  const setStateCopy = newVal => {
    ref.current = newVal;
    setState(newVal);
  };
  const getState = () => ref.current;
  return [state, setStateCopy, getState];
};

https://ahooks.js.org/hooks/use-get-state

function useGetState<S>(initialState?: S) {
  const [state, setState] = useState(initialState);
  const stateRef = useRef(state);
  stateRef.current = state;

  const getState = useCallback(() => stateRef.current, []);

  return [state, setState, getState];
}

export default useGetState;