0%

用useRef来封装usePrevious

1
2
3
4
5
6
7
8
9
10
11
12
13
import { useRef, useEffect } from 'react';

const usePrevious = value => {

const ref = useRef();

useEffect(() => {
ref.current = value;
}, [value]);

return ref.current;

}

为什么用useRef能拿到上一次的值。

  1. useRef保持引用不变;
  2. 函数式组件的生命周期决定,JSX的渲染比useEffect早。
  3. 手动修改ref.current并不会触发组件的重新渲染。