react-use-count-up
Version:
A React hook with Typescript typings for animating a number counting up
71 lines (70 loc) • 3.1 kB
JavaScript
import { useEffect, useState } from 'react';
import { easeInCubic, easeInExpo, easeInQuad, easeInQuart, easeInQuint, easeOutCubic, easeOutExpo, easeOutQuad, easeOutQuart, easeOutQuint, linear } from './easing-functions';
var fps = 60;
var intervalDelay = Math.round(1 / fps * 1000);
export var useCountUp = function (_a) {
var start = _a.start, end = _a.end, duration = _a.duration, _b = _a.started, started = _b === void 0 ? true : _b, formatter = _a.formatter, easingFunction = _a.easingFunction;
var _c = useState(start), value = _c[0], setValue = _c[1];
useEffect(function () {
if (started) {
// determine the easing function to use
var fn_1;
if (typeof easingFunction === 'function') {
fn_1 = easingFunction;
}
else if (easingFunction === 'linear') {
fn_1 = linear;
}
else if (easingFunction === 'easeOutExpo') {
fn_1 = easeOutExpo;
}
else if (easingFunction === 'easeInExpo') {
fn_1 = easeInExpo;
}
else if (easingFunction === 'easeOutQuad') {
fn_1 = easeOutQuad;
}
else if (easingFunction === 'easeInQuad') {
fn_1 = easeInQuad;
}
else if (easingFunction === 'easeOutCubic') {
fn_1 = easeOutCubic;
}
else if (easingFunction === 'easeInCubic') {
fn_1 = easeInCubic;
}
else if (easingFunction === 'easeOutQuart') {
fn_1 = easeOutQuart;
}
else if (easingFunction === 'easeInQuart') {
fn_1 = easeInQuart;
}
else if (easingFunction === 'easeOutQuint') {
fn_1 = easeOutQuint;
}
else if (easingFunction === 'easeInQuint') {
fn_1 = easeInQuint;
}
else {
fn_1 = easeOutExpo; // default
}
var time_1 = 0;
var change_1 = end - start;
var intervalId_1 = setInterval(function () {
// check to see if we're at the end
if (time_1 >= duration) {
setValue(end); // skip the calculation and use the end number directly
clearInterval(intervalId_1); // we don't need the interval anymore
return;
}
// set the new value based on the easing function
setValue(fn_1(time_1, start, change_1, duration));
// increase the time value based on the interval delay
time_1 += intervalDelay;
}, intervalDelay);
// clear the interval on unmount/props change
return function () { return clearInterval(intervalId_1); };
}
}, [start, end, duration, started, easingFunction]);
return formatter ? formatter(value) : value.toFixed(0);
};