useTimeout
Manage timeouts conveniently using the useTimeout hook.
The useTimeout
hook is helpful when you want to setup a timeout callback from your components. It can be helpful in cases when you want to perform a delayed action or a timed event for maybe an animation or clearing loading states.
It automatically cleans up the timeout created by the window.setTimeout
API when component unmounts and also returns an cancelTimeout
method to cancel the the timeout programatically.
The hook relies on the setTimeout (MDN) method available on browsers.
useTimeout
Counter Value: 0
Counter value increments for 5s and then resets back to zeroUsage
Import the hook from @abhushanaj/react-hooks
and use in required component;
Properties
- When using the
useTimeout
hook, you don’t need to memoize the callback withReact.useCallback
or similar. As the callback is not utilized as a dependency in theReact.useEffect
, you can pass your callback as is, and rest assured that it will be called correctly after the delay.
API Reference
Parameters
Parameter | Type | Description | Default |
---|---|---|---|
callback | ()=>void | The callback function to execute after the delay period. | N/A |
duration | number (optional) | The duration of timeout in ms . | 0 |
Return Value
The return value follows the signature [cancelTimeout]
.
Parameter | Type | Description | Default |
---|---|---|---|
cancelTimeout | ()=>void | A function to clear the timeout and stop the delayed execution. | N/A |