-
Notifications
You must be signed in to change notification settings - Fork 132
/
useCountUp.js
79 lines (68 loc) · 2.2 KB
/
useCountUp.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import { useEffect, useRef, useState } from 'react';
import CountUp from './CountUp';
import { createCountUpInstance } from './common';
// CountUp.js requires an element to execute it's animation,
// since it only checks for truthy values -1 is enough to mock an element.
const NO_ELEMENT = -1;
const useCountUp = props => {
const _props = { ...CountUp.defaultProps, ...props };
const { start, formattingFn } = _props;
const [count, setCount] = useState(
typeof formattingFn === 'function' ? formattingFn(start) : start,
);
const countUpRef = useRef(null);
const createInstance = () => {
const countUp = createCountUpInstance(NO_ELEMENT, _props);
let formattingFnRef = countUp.options.formattingFn;
countUp.options.formattingFn = (...args) => {
const result = formattingFnRef(...args);
setCount(result);
};
return countUp;
};
const getCountUp = () => {
const countUp = countUpRef.current;
if (countUp !== null) {
return countUp;
}
const newCountUp = createInstance();
countUpRef.current = newCountUp;
return newCountUp;
};
const reset = () => {
const { onReset } = _props;
getCountUp().reset();
onReset({ pauseResume, start: restart, update });
};
const restart = () => {
const { onStart, onEnd } = _props;
getCountUp().reset();
getCountUp().start(() => {
onEnd({ pauseResume, reset, start: restart, update });
});
onStart({ pauseResume, reset, update });
};
const pauseResume = () => {
const { onPauseResume } = _props;
getCountUp().pauseResume();
onPauseResume({ reset, start: restart, update });
};
const update = newEnd => {
const { onUpdate } = _props;
getCountUp().update(newEnd);
onUpdate({ pauseResume, reset, start: restart });
};
useEffect(() => {
const { delay, onStart, onEnd } = _props;
const timeout = setTimeout(() => {
onStart({ pauseResume, reset, update });
getCountUp().start(() => {
clearTimeout(timeout);
onEnd({ pauseResume, reset, start: restart, update });
});
}, delay * 1000);
return reset;
}, []);
return { countUp: count, start: restart, pauseResume, reset, update };
};
export default useCountUp;