Let's start with some nonsense
useUpdateEffect
& nbsp; usage is equivalent to & nbsp;useEffect
, but ignores execution for the first time, only if it depends on updates.
there are scenarios in which we do not want to perform effect when rendering for the first time, such as when searching, the search method is called only when the keyword changes. This hooks is also used more often in daily work, so it is necessary for us to write its source code, 🤓.
Let's see the effect
for the first time, only useEffect prints count, and only when count changes, useUpdateEffect
prints count
Source code implementation
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]);
};
complete demo source code
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('count' of useEffect, count);
}, [count]);
useUpdateEffect(() => {
console.log('count' of useUpdateEffect, count);
}, [count]);
return (
<>
<div>Count: {count}</div>
<Button type="primary" onClick={() => setCount(count + 1)}>
Click me + 1
</Button>
</>
);
};
export default Demo;
reference
interested friends can look at the source code of react-use and ahooks to learn the elegant code of their predecessors.
Comments