https://github.com/flaque/use-timeout
A react-hook for accessing setTimeout without constantly resetting.
https://github.com/flaque/use-timeout
Last synced: 10 days ago
JSON representation
A react-hook for accessing setTimeout without constantly resetting.
- Host: GitHub
- URL: https://github.com/flaque/use-timeout
- Owner: Flaque
- Created: 2019-10-10T20:18:07.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2021-08-11T13:44:56.000Z (almost 4 years ago)
- Last Synced: 2024-11-11T13:52:33.057Z (6 months ago)
- Language: TypeScript
- Homepage:
- Size: 31.3 KB
- Stars: 4
- Watchers: 2
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# use-timeout
[](https://github.com/flaque/use-timeout/blob/master/package.json)
A react-hook for accessing setTimeout without constantly resetting.
## Install
```
yarn add @flaque/use-timeout
```## Usage
```ts
const [setTimeoutHook, clearTimeoutHook] = useTimeout();setTimeoutHook(() => {
console.log("It's been 10000 miliseconds!");
}, 10000);// ...
clearTimeoutHook(); // Stops the timeout before it happens
```## Why?
If you call `setTimeout` inside of a function component like this:
```ts
// BAD DONT DO THIS
function MyComponent() {
const [isLoading, setIsLoading] = useState(false)
setTimeout(() => {
setIsLoading(true)
}, 1000)
return{isLoading ? "loading" : "finished"}
}
// BAD DONT DO THIS
```Then it'll get reset when the function renders. That can lead to weird unexpected behavior. `use-timeout` uses hooks to keep an internal reference to the timeout to avoid any weirdness.