useElapsedTime React hook
The only hook you need to perform JavaScript animations in React.
- Lightweight: only 2.4kB min / 1.1kB min+gzip
- Built with 0 dependencies
- Toggle play/pause
- Combine with any easing function to get the right animation
- Built-in and ready-to-use TypeScript type definitions.
Installation
yarn add use-elapsed-time
or
npm install use-elapsed-time
Basic usage
import { useElapsedTime } from 'use-elapsed-time';
const MyComponent = () => {
const isPlaying = true;
const elapsedTime = useElapsedTime(isPlaying);
return elapsedTime;
};
Basic usage demo
Function signature
function useElapsedTime(
isPlaying: boolean,
config?: {
durationMilliseconds: number,
onComplete?: () => undefined | [shouldRepeat: boolean, delay: number]
}
): number;
The first argument isPlaying
indicates if the loop to get the elapsed time is running or it is paused.
The second argument config
is optional and it makes sense when the animation duration durationMilliseconds
is defined. onComplete
callback will be fired when the duration is reached. onComplete
can be used to restart the elapsed time loop by returning an array where the first element shouldRepeat
indicates if the loop should start over and second element delay
specifies the delay before looping again in milliseconds.
The hook returns elapsed time in milliseconds.
Use cases
Countdown timer
Count up animation
Non-liner path animation
1.1.4 (December 19th, 2019)
Implemented enhancements:
- Add a new config option "startAt" to change the start time of the animation. Defaults to 0 if not provided