ahooks/usePrevious学习

677 阅读1分钟

1. usePrevious 解决了什么问题?

简介: usePrevious用于保存上一次渲染时的状态。

  • 简单看一下它的用法
// 基础用法:记录上次的 count 值
import { usePrevious } from 'ahooks';
import React, { useState } from 'react';

export default () => {
  const [count, setCount] = useState(0);
  const previous = usePrevious(count);
  return (
    <>
      <div>counter current value: {count}</div>
      <div style={{ marginBottom: 8 }}>counter previous value: {previous}</div>
      <button type="button" onClick={() => setCount((c) => c + 1)}>
        increase
      </button>
      <button type="button" style={{ marginLeft: 8 }} onClick={() => setCount((c) => c - 1)}>
        decrease
      </button>
    </>
  );
};

2.如何实现

  • React官方文档提供了一个实现
// usePrevious记录的值初始为空,每轮渲染后记录状态值,这样每次渲染返回的便是上一轮渲染时的值。
function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
}