实现useState改变值之后立刻获取最新的状态

257 阅读1分钟

1、 实现useState改变值之后立刻获取最新的状态

import { useEffect, useState, useCallback } from 'react';

const useSyncCallback = (callback: () => void) => {
  const [proxyState, setProxyState] = useState({ current: false });

  const Func = useCallback(() => {
    setProxyState({ current: true });
  }, [proxyState]);

  useEffect(() => {
    if (proxyState.current === true) setProxyState({ current: false });
  }, [proxyState]);

  useEffect(() => {
    proxyState.current && callback();
  });

  return Func;
};

export default useSyncCallback;