useRef 存储的数据不会因为组件的更新渲染而被重新初始化

基于 useRef 创建名为 prevCountRef 的数据对象,用来存储上一次的旧 count 值,每当点击按钮触发 count 自增时,都把最新的旧值传递给 prevCountRef.current 即可

const App: React.FC = () => {
  
  const [count, setCount] = useState<number>(0);
  const prevCount = useRef<number>();

  const update = () => {
    setCount(count + 1); // 异步更新

    prevCount.current = count // 这里得到旧值
  };

  return (
    <div>
      <h1>previous count: {prevCount.current}</h1>
      <h1>new count: {count}</h1>
      <button onClick={update}>update</button>
    </div>
  );
};