This article has participated in the activity of “New person creation Ceremony”, and started the road of digging gold creation together.
Hello, everyone, I’m Little Dudu. Sometimes when we want to do activities, we often have the function of countdown, or some common side effects, throttling or shaking prevention. These side effects can be realized through a simple Hook, and the next part will be explained gradually
Learning from ahooks requires that you learn with the attitude that you may not, but you can’t help but know, in case you do
The value can be set by setInterval, setInterval, useCountDown, useDebounce, useDebounceFn, useThrottle, useThrottleFn, and useLockFn
As before we marked the importance of the hook by ⭐️
⭐️ : General; ⭐️⭐️ : important; ⭐️⭐️ port: Very important
The special hook useReactive can help you a lot. When the special hooks are special, the special hook useReactive can help you a lot.
Example: Domesy/ahook
UseInterval Specifies the function used to manage setInterval
Recommended Index ⭐️⭐️ useInterval: A function that is executed at regular intervals, similar to polling
- Fn: function called repeatedly
- Delay: Interval time, when the value is null or undefined will stop the timer
- Option: object containing immediate (whether to render for the first time, false by default)
Code sample
import React, { useState } from 'react';
import { Button } from 'antd';
import { useInterval } from 'ahooks';
const Test: React.FC<any> = () = > {
const [count, setCount] = useState(0);
useInterval(() = > {
setCount(count + 1);
}, 1000);
return (
<>
<div style={{fontWeight: 'bolder'}} >Basic usage:</div>
<div style={{marginTop: 8}} >Every 1000ms, increment the number by 1: {count}</div>
</>
);
}
const Mock: React.FC<any> = () = > {
const [count, setCount] = useState(0);
const [interval, setInterval] = useState<number | null> (1000);
useInterval(
() = > {
setCount(count + 1);
},
interval,
{ immediate: true});return (
<>
<Test />
<div style={{fontWeight: 'bolder'}} >Advanced usage:</div>
<div style={{marginTop: 8}} >Every {interval | | 0} ms, number 1: {count}</div>
<div style={{marginTop: 8}} >Interval: {interval}</div>
<div style={{marginTop: 8.display: 'flex', justifyContent: 'flex-start'}} >
<Button type='primary' style={{marginRight: 16}} onClick={()= >{if(typeof interval === 'number') setInterval(interval + 1000)}}> add 1s</Button>
<Button type='primary' style={{marginRight: 16}} onClick={()= >SetInterval (1000)} > reset</Button>
<Button type='primary' style={{marginRight: 16}} onClick={()= >SetInterval (null)} ></Button>
</div>
</>
);
};
export default Mock;
Copy the code
UseTimeout Specifies the function used to manage setInterval
Recommended Index ⭐️⭐️
UseTimeout: Hooks that handle timer functions
- Fn: function called repeatedly
- Delay: Interval time, when the value is null or undefined will stop the timer
Code examples:
import React, { useState } from 'react';
import { Button } from 'antd';
import { useTimeout } from 'ahooks';
const Mock: React.FC<any> = () = > {
const [count, setCount] = useState(0);
useTimeout(() = > {
setCount(count + 1);
}, 2000);
return (
<div>2000ms + 1: {count}</div>
);
};
export default Mock;
Copy the code
UseCountDown countdown
Recommended Index ⭐️⭐️ service board
useCountDown
- First, there are two values, one is the target value (targetDate), one is the setting value, if you do not set the initial value (setTargetDate), the default is now
- Countdown will automatically count the days, months and weeks from the target as well as the timestamp (countdown) of the target value. Note that the units are milliseconds, so math.round (countdown / 1000) is accurate to the second.
- Has a common countdown function, and can control the function triggered when stopping (onEnd)
Code sample
import React, { useEffect } from 'react';
import { Button, message } from 'antd';
import { useBoolean } from 'ahooks';
import { Method } from '@/utils';
const CountDownTest1: React.FC<any> = () = > {
const [targetDate, setTargetDate] = useState<any>(Method.getDate({add: 3}));
const [countdown, formattedRes] = useCountDown({
targetDate,
});
useEffect(() = > {
setTargetDate(Method.getDate({add: 2}})), [])const { days, hours, minutes, seconds, milliseconds } = formattedRes;
return <div>{days} days, {hours} hours {minutes} minutes {seconds} seconds {milliseconds}</div>
}
const CountDownTest2: React.FC<any> = () = > {
const [targetDate, setTargetDate] = useState<any>(Method.getDate({add: 3}));
const [countdown, formattedRes] = useCountDown({
targetDate,
onEnd: () = > {
message.info('Stopped! ')}});return <div style={{display: 'flex',justifyContent: 'flex-start'}} >The countdown:<Button style={{margin: '0 24px'}} type='primary' onClick={()= >{ setTargetDate(Date.now() + 60000); }}>{countdown === 0 ? 'countdown' : "math.round (countdown / 1000)}s"</Button>
<Button onClick={()= >{ setTargetDate(undefined); }} > stop</Button>
</div>
}
const CountDownTest1: React.FC<any> = () = > {
const [targetDate, setTargetDate] = useState<any>(Method.getDate({add: 3}));
const [countdown, formattedRes] = useCountDown({
targetDate,
});
useEffect(() = > {
setTargetDate(Method.getDate({add: 2}})), [])const { days, hours, minutes, seconds, milliseconds } = formattedRes;
return <div>{days} days, {hours} hours {minutes} minutes {seconds} seconds {milliseconds}</div>
}
const CountDownTest2: React.FC<any> = () = > {
const [targetDate, setTargetDate] = useState<any>(Method.getDate({add: 3}));
const [countdown, formattedRes] = useCountDown({
targetDate,
onEnd: () = > {
message.info('Stopped! ')}});return <div style={{display: 'flex',justifyContent: 'flex-start'}} >The countdown:<Button style={{margin: '0 24px'}} type='primary' onClick={()= >{ setTargetDate(Date.now() + 60000); }}>{countdown === 0 ? 'Countdown' : math.round (countdown / 1000)}s</Button>
<Button onClick={()= >{ setTargetDate(undefined); }} > stop</Button>
</div>
}
const Mock: React.FC<any> = () = > {
const [countdown, formattedRes] = useCountDown({
targetDate: Method.getDate({add: 1})});const { days, hours, minutes, seconds, milliseconds } = formattedRes;
return (
<>
<div>{days} days, {hours} hours {minutes} minutes {seconds} seconds {milliseconds}</div>
<div></div>
<CountDownTest1 />
<div></div>
<CountDownTest2 />
</>
};
export default Mock;
Copy the code
UseDebounce Anti-shake of the value
Recommended Index ⭐️
Const debouncedValue = useDebounce(value: any, {wait: number}])
Value: indicates the security value. Wait: indicates the timeout period
Code sample
import React, { useState } from 'react';
import { Button } from 'antd';
import { useDebounce } from 'ahooks';
const Mock: React.FC<any> = () = > {
const [value, setValue] = useState<string> (' ');
const debouncedValue = useDebounce(value, { wait: 500 });
return (
<div>
<input
value={value}
onChange={(e)= > setValue(e.target.value)}
placeholder="Typed value"
style={{ width: 280 }}
/>
<p style={{ marginTop: 16}} >{debouncedValue}</p>
</div>
);
};
export default Mock;
Copy the code
UseDebounceFn Is used to stabilize functions
Recommended Index ⭐️
UseDebounceFn: A hook that defends a function by calling run frequently but only once
Const {run, cancel, flush} = useDebounceFn(fn: (… args:any) => any, { wait: number})
Run, cancel, flush run, cancel, flush
Code sample
import React, { useState } from 'react';
import { Button } from 'antd';
import { useDebounceFn } from 'ahooks';
const Mock: React.FC<any> = () = > {
const [value, setValue] = useState(0);
const { run } = useDebounceFn(
() = > {
setValue(value + 1);
},
{
wait: 500,});return (
<div>
<p style={{ marginTop: 16}} >Valid clicks: {value}</p>
<Button type="primary" onClick={()= >{run()}}> Quick click</Button>
</div>
);
};
export default Mock;
Copy the code
UseThrottle throttling of values
Recommended Index ⭐️
UseThrottle: A hook that throttles a value calls the run method frequently, but only once
Const throttledValue = useThrottle(value: any, {wait: number})
Code examples:
import React, { useState } from 'react';
import { Button } from 'antd';
import { useThrottle } from 'ahooks';
const Mock: React.FC<any> = () = > {
const [value, setValue] = useState<string> ();const throttledValue = useThrottle(value, { wait: 500 });
return (
<div>
<input
value={value}
onChange={(e)= >SetValue (e.targe. value)} placeholder=" input value "style={{width: 280}} /><p style={{ marginTop: 16}} >Changes every 500ms: {throttledValue}</p>
</div>
);
};
export default Mock;
Copy the code
UseThrottleFn Throttling of a function
Recommended Index ⭐️
UseThrottleFn: a hook that throttles functions, calling run frequently but only executing related functions once every 500ms.
Const {run, cancel, flush} = useThrottleFn(fn: (… args:any) => any, { wait: number})
Run (function for throttling), Cancel (cancel current throttling), Flush (called immediately for current throttling)
Code sample
import React, { useState } from 'react';
import { Button } from 'antd';
import { useThrottleFn } from 'ahooks';
const Mock: React.FC<any> = () = > {
const [value, setValue] = useState(0);
const { run } = useThrottleFn(
() = > {
setValue(value + 1);
},
{ wait: 500});return (
<div>
<p style={{ marginBottom: 16}} > Clicked count: {value} </p>
<Button type='primary' onClick={run}>A quick click</Button>
</div>
);
};
export default Mock;
Copy the code
UseLockFn static lock
Recommended Index ⭐️⭐️ service board
UseLockFn: Used to add a race lock to an asynchronous function to prevent concurrent execution.
When we in the form is submitted, the order may be because the user’s wrong operation such as repeated submission, this is some friend said the use of image stabilization, actually if you are not the best choice, the best way is a static lock, if the current method is not performed, will not be effective again, not as if you have a few seconds of time, so this hook is very important
Code sample
import React, { useState } from 'react';
import { Button } from 'antd';
import { useLockFn } from 'ahooks';
function mockApiRequest() {
return new Promise((resolve:any) = > {
setTimeout(() = > {
resolve();
}, 2000);
});
}
const Mock: React.FC<any> = () = > {
const [count, setCount] = useState(0);
const submit = useLockFn(async () => {
message.info('Start execution')
await mockApiRequest();
setCount((v) = > v + 1)
message.info('End of execution')})return (
<>
<div>Number of clicks: {count}</div>
<Button style={{marginTop: 8}} type='primary' onClick={submit} >Click on the</Button>
</>
);
};
export default Mock;
Copy the code