跳到主要内容

useLatest

跟踪 React State 的最新值。

Usage

实时编辑器

function Demo() {
  const [count, setCount] = useState(0);
  const latestCount = useLatest(count);
  const handleAlertClick = () => {
    setTimeout(() => {
      alert(`Latest count value: ${latestCount.current}`);
    }, 3000);
  };

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
      <button onClick={handleAlertClick}>Show alert</button>
    </div>
  );
};

结果
Loading...

API

useLatest

Returns

React.MutableRefObject<T>: ref 对象

Arguments

参数名描述类型默认值
value追踪值T (必填)-