https://github.com/termosa/use-interval-value
Generate new values at intervals
https://github.com/termosa/use-interval-value
Last synced: about 1 year ago
JSON representation
Generate new values at intervals
- Host: GitHub
- URL: https://github.com/termosa/use-interval-value
- Owner: termosa
- Created: 2020-11-05T07:33:52.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2020-11-05T08:47:24.000Z (over 5 years ago)
- Last Synced: 2025-02-10T12:43:54.630Z (over 1 year ago)
- Language: TypeScript
- Size: 632 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# use-interval-value
> Generate new values at intervals
[](https://www.npmjs.com/package/use-interval-value) [](https://standardjs.com)
## Install
```bash
npm install use-interval-value
```
## Usage
```tsx
import * as React from 'react'
import useIntervalValue from 'use-interval-value'
const getCurrentTime = () => new Date().toString().slice(16, 24)
export const Time = () => {
const time = useIntervalValue(1000, getCurrentTime)
return
{time}
}
```
### With mutable callback
```tsx
import * as React from 'react'
import useIntervalValue, { IntervalCallback } from 'use-interval-value'
const second = 1e3
const minute = second * 60
const hour = minute * 60
const formatTimeLeft = (msLeft: number) => {
const hours = Math.floor(msLeft / hour).toString().padStart(2, '0')
const minutes = Math.floor((msLeft % hour) / minute).toString().padStart(2, '0')
const seconds = Math.ceil((msLeft % minute) / second).toString().padStart(2, '0')
return `${hours}:${minutes}:${seconds}`
}
export const Countdown = ({ endTimestamp }: { endTimestamp: number }) => {
const getTimeLeft = React.useCallback>(
clear => {
const timeLeft = endTimestamp - Date.now()
if (timeLeft <= 0) clear()
return formatTimeLeft(timeLeft < 0 ? 0 : timeLeft)
},
[endTimestamp]
)
const time = useIntervalValue(1000, getTimeLeft)
return
{time}
}
Countdown.defaultProps = {
endTimestamp: Date.now() + 1e4,
}
```
## License
MIT © [termosa](https://github.com/termosa)
---
This hook is created using [create-react-hook](https://github.com/hermanya/create-react-hook).