AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

use-count-up.ts 1.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { useEffect, useRef, useState } from 'react';
  2. import { prefersReducedMotion } from '@/components/overview/format';
  3. /** A number that counts up (or down) to its new value, so changes are easy to notice. */
  4. export function useCountUp(target: number, duration = 900): number {
  5. const [value, setValue] = useState(() =>
  6. prefersReducedMotion() ? target : 0,
  7. );
  8. const from = useRef(value);
  9. useEffect(() => {
  10. if (prefersReducedMotion()) {
  11. from.current = target;
  12. setValue(target);
  13. return;
  14. }
  15. const start = performance.now();
  16. const begin = from.current;
  17. let frame = 0;
  18. const step = (now: number) => {
  19. const progress = Math.min(1, (now - start) / duration);
  20. const eased = 1 - Math.pow(1 - progress, 3);
  21. const next = begin + (target - begin) * eased;
  22. from.current = next;
  23. setValue(next);
  24. if (progress < 1) {
  25. frame = requestAnimationFrame(step);
  26. }
  27. };
  28. frame = requestAnimationFrame(step);
  29. return () => cancelAnimationFrame(frame);
  30. }, [target, duration]);
  31. return value;
  32. }