@fdaciuk/use-timer
v0.2.1
Published
React Hook to easily create decremental timers
Downloads
33
Readme
use-timer
React Hook to easily create decremental timers
Install
npm install --save @fdaciuk/use-timer
If you are using yarn:
yarn add @fdaciuk/use-timer
Usage
import React, { useEffect } from 'react'
import useTimer from '@fdaciuk/use-timer'
function Example () {
const { minutes, seconds, start } = useTimer('05:00')
useEffect(() => {
start()
}, [start])
return (
<div>{minutes}:{seconds}</div>
)
}
Complete example
import React, { useCallback, useEffect } from 'react'
import useTimer from '@fdaciuk/use-timer'
function Example () {
const {
minutes,
seconds,
start,
pause,
finished,
reset,
setTimer
} = useTimer('05:00')
const handleSubmit = useCallback((e) => {
e.preventDefault()
setTimer(e.target.elements.time.value)
}, [setTimer])
useEffect(() => {
finished(() => {
console.log('finished!')
})
}, [finished])
return (
<>
<h1>{minutes}:{seconds}</h1>
<button onClick={start}>Start!</button>
<button onClick={pause}>Pause</button>
<button onClick={reset}>Reset timer</button>
<form onSubmit={handleSubmit}>
<input type='text' name='time' />
<button type='submit'>Set new timer</button>
</form>
</>
)
}
Properties and methods
minutes
(String
): show left minutes in 2 or more digitsseconds
(String
): show left seconds in 2 or more digitsstart
(Function
): function that should be executed when the timer is supposed to start countingpause
(Function
): function to pause timer,finished
(Function
): function that receives another function that will be executed when timer finishes countingreset
(Function
): function to reset counter to it's initial time, passed touseTimer
hooksetTimer
(Function
): function to set a new timer
License
MIT © fdaciuk