Timer and Countdown hook for React.
Installation
Using npm:
$ npm install --save react-timehook
Using yarn:
$ yarn add react-timehook
Quick Start
import React from 'react';
import useCountDown from 'react-timehook';
const initialTime = 60 * 1000; // initial time in milliseconds, defaults to 60000
const interval = 1000; // interval to change remaining time amount, defaults to 1000
const render = () => {
const { currentTimer, onStartTimer, onResetTimer, isFinish } = timerhook(
{
initialTimer: 60,
mode: 'COUNTDOWN_SECOND',
}
)
// start the timer during the first render
React.useEffect(() => {
onStartTimer();
}, []);
const restart = React.useCallback(() => {
// you can start existing timer with an arbitrary value
// if new value is not passed timer will start with initial value
onResetTimer(100);
}, []);
return (
<>
<p>Time left: {timeLeft}</p>
{isFinish ? <b>FINISH</b> : ''}
<button onClick={restart}>
Restart counter with 100 seconds
</button>
</>
);
}
Documentation
[timeLeft, actions] = useCountDown(timeToCount, interval)
Parameters
Takes a default countdown time and interval time.
-
initialTimer
{Number
} Time in milliseconds that countdown should start with. Defaults to60000
-
mode
{String
} Time mode set toCOUNTDOWN_SECOND
Defaults tonull
Return value
Returns an array with remaining time and actions object.
-
currentTimer
{Number
} Remaining countdown time in milliseconds -
onStartTimer
{Function
} Start or restart a countdown. Takes time in milliseconds to start with. -
onResetTimer
{Function
} Resets a countdown to initial state
Contributing
Feel free to submit any issues or pull requests.
License
MIT