Use Animated Number
dashboardblocks/use-animated-numberFreeHook
A hook for animating a number.
Live preview
live · rendered by the registry
Rendered by dashboardblocks on their own page — this is the component running, not a screenshot of it.Install it
npx shadcn@latest add https://dashboardblocks.com/r/use-animated-number.jsonSource
1'use client'23import { useInView } from '@/registry/hooks/use-in-view'4import { useCallback, useEffect, useRef, useState } from 'react'56type EasingFunction = (t: number) => number78const easings: Record<string, EasingFunction> = {9 linear: (t) => t,10 easeOut: (t) => 1 - Math.pow(1 - t, 3),11 easeIn: (t) => t * t * t,12 easeInOut: (t) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2),13 spring: (t) => 1 - Math.pow(Math.cos(t * Math.PI * 0.5), 3),14}1516interface UseAnimatedNumberOptions {17 /**18 * Duration of the animation in milliseconds19 * @default 100020 */21 duration?: number22 /**23 * Easing function for the animation24 * @default 'easeOut'25 */26 easing?: keyof typeof easings | EasingFunction27 /**28 * Starting value for the animation29 * @default 030 */31 from?: number32 /**33 * Intersection Observer threshold (0-1)34 * @default 0.135 */36 threshold?: number37 /**38 * Intersection Observer root margin39 * @default '0px'40 */41 rootMargin?: string42 /**43 * Delay before starting animation in milliseconds44 * @default 045 */46 delay?: number47 /**48 * Whether to re-animate when element comes back into view49 * @default false50 */51 reanimateOnView?: boolean52}5354export function useAnimatedNumber(to: number, options: UseAnimatedNumberOptions = {}) {55 const {56 delay = 0,57 duration = 1000,58 easing = 'easeOut',59 from = 0,60 reanimateOnView = false,61 rootMargin = '0px',62 threshold = 1.0,63 } = options6465 const [value, setValue] = useState(from)66 const [isAnimating, setIsAnimating] = useState(false)67 const hasAnimated = useRef(false)68 const animationRef = useRef<number | null>(null)69 const timeoutRef = useRef<NodeJS.Timeout | null>(null)7071 const { isInView, ref } = useInView({ rootMargin, threshold })7273 const decimals = to.toString().split('.')[1]?.length || 07475 const easingFn =76 typeof easing === 'function' ? easing : easings[easing] || easings.easeOut7778 const animate = useCallback(() => {79 if (animationRef.current) {80 cancelAnimationFrame(animationRef.current)81 }8283 const startTime = performance.now()84 const startValue = from8586 setIsAnimating(true)8788 const tick = (currentTime: number) => {89 const elapsed = currentTime - startTime90 const progress = Math.min(elapsed / duration, 1)91 const easedProgress = easingFn(progress)92 const currentValue = startValue + (to - startValue) * easedProgress9394 setValue(95// … truncated
What it pulls in
Other registry items
Files it writes
More from dashboardblocks
All 36 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| Use In Viewuse-in-view | dashboardblocks | Hooks | Free | no deps |
