每天一个hooks —— useUpdateEffect
🐶先讲点废话
useUpdateEffect
用法等同于useEffect
,但是会忽略首次执行,只在依赖更新时执行。
有些场景我们不想在首次渲染时就执行 effect,比如搜索时,只在 keyword 变化时才调用 search 方法。这个hooks在平时工作中也用的比较多的,所以我们来写写它的源码还是很有必要的🤓。
🦌来看看效果
可以看到,第一次只有useEffect会打印count,只有count变化时,useUpdateEffect
才会打印出count
🐿源码实现
import React, { useEffect, useRef } from 'react';
const useUpdateEffect = (
effect: React.EffectCallback,
deps: React.DependencyList,
) => {
let isFirst = useRef(true);
useEffect(() => {
if (isFirst.current) {
isFirst.current = false;
return;
}
return effect();
}, [deps]);
};
🐬完整demo源码
import React, { useEffect, useRef } from 'react';
import { Button } from 'antd';
const useUpdateEffect = (
effect: React.EffectCallback,
deps: React.DependencyList,
) => {
let isFirst = useRef(true);
useEffect(() => {
if (isFirst.current) {
isFirst.current = false;
return;
}
return effect();
}, [deps]);
};
const Demo = () => {
const [count, setCount] = React.useState(0);
useEffect(() => {
console.log('useEffect的count', count);
}, [count]);
useUpdateEffect(() => {
console.log('useUpdateEffect的count', count);
}, [count]);
return (
<>
<div>Count: {count}</div>
<Button type="primary" onClick={() => setCount(count + 1)}>
点我+ 1
</Button>
</>
);
};
export default Demo;
🍓参考
转载自:https://juejin.cn/post/7226903867580334141