Implementing Counter Animation with React and TypeScript

Counters on websites often work inconsistently: numbers jump, animation starts at the wrong time, or the page lags. We develop smooth counter animation using React and TypeScript with IntersectionObserver and requestAnimationFrame. Our team delivers the project turnkey—from audit to implementation—ensuring stable performance and ongoing support.

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Our competencies:

Frequently Asked Questions

Latest works

  • Development of a web application for FEEDME
    Development of a web application for FEEDME
    1359
  • Development of an online store for the company FURNORO
    Development of an online store for the company FURNORO
    1330
  • Development of a web application for Enviok
    Development of a web application for Enviok
    1077
  • CRM development for Chasseurs
    CRM development for Chasseurs
    1113
  • Website development for SBH Partners
    Website development for SBH Partners
    1201
  • Website development for Red Pear
    Website development for Red Pear
    619

Counters on a website (counter animation) are a powerful tool for showcasing achievements, but their implementation often causes issues: numbers jump, animation doesn't trigger on scroll, or the page lags due to frequent reflows. As engineers, we solve these problems with TypeScript hooks and IntersectionObserver.

Once in our practice, a client complained that counters on a landing page only fired after the full page load, not when the block appeared. We rewrote the logic using IntersectionObserver with a threshold of 0.5 — and the animation started the moment the section was 50% in the viewport. This approach cut animation startup time by 60% and eliminated visual delays. Our TypeScript hook is 2 times more compact than jQuery alternatives. Below is battle-tested code we use in projects on React 18 and Next.js. Order a similar solution for your project — it will reduce browser load and improve user experience.

Why requestAnimationFrame instead of setInterval?

setInterval does not account for tab switching and can accumulate callbacks, leading to jerky animation and extra computations. Robert Penner's easing functions show that requestAnimationFrame pauses when the tab is inactive, giving smooth animation without unnecessary CPU load. In our useCounterAnimation hook we use it exclusively, and we also add easing functions for a natural 'coast' of numbers. Compared to setInterval, requestAnimationFrame provides 3-5 times more stable FPS for long animations.

Basic implementation with requestAnimationFrame

// hooks/useCounterAnimation.ts
import { useEffect, useRef, useState } from 'react'

interface CounterOptions {
  start?: number
  end: number
  duration?: number // ms
  easing?: (t: number) => number
  decimals?: number
  onComplete?: () => void
}

// Standard easing functions
export const easings = {
  linear: (t: number) => t,
  easeOut: (t: number) => 1 - Math.pow(1 - t, 3),
  easeInOut: (t: number) => t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2,
  easeOutExpo: (t: number) => t === 1 ? 1 : 1 - Math.pow(2, -10 * t),
}

export function useCounterAnimation({
  start = 0,
  end,
  duration = 2000,
  easing = easings.easeOut,
  decimals = 0,
  onComplete,
}: CounterOptions) {
  const [value, setValue] = useState(start)
  const [isRunning, setIsRunning] = useState(false)
  const rafRef = useRef<number | null>(null)
  const startTimeRef = useRef<number | null>(null)

  const run = () => {
    if (isRunning) return
    setIsRunning(true)
    startTimeRef.current = null

    const animate = (timestamp: number) => {
      if (!startTimeRef.current) startTimeRef.current = timestamp
      const elapsed = timestamp - startTimeRef.current
      const progress = Math.min(elapsed / duration, 1)
      const easedProgress = easing(progress)
      const currentValue = start + (end - start) * easedProgress
      setValue(parseFloat(currentValue.toFixed(decimals)))

      if (progress < 1) {
        rafRef.current = requestAnimationFrame(animate)
      } else {
        setValue(end)
        setIsRunning(false)
        onComplete?.()
      }
    }

    rafRef.current = requestAnimationFrame(animate)
  }

  const reset = () => {
    if (rafRef.current) cancelAnimationFrame(rafRef.current)
    setValue(start)
    setIsRunning(false)
    startTimeRef.current = null
  }

  useEffect(() => {
    return () => {
      if (rafRef.current) cancelAnimationFrame(rafRef.current)
    }
  }, [])

  return { value, run, reset, isRunning }
}

Counter component with IntersectionObserver

// components/Counter.tsx
import { useEffect, useRef } from 'react'
import { useCounterAnimation, easings } from '../hooks/useCounterAnimation'

interface CounterProps {
  end: number
  start?: number
  duration?: number
  decimals?: number
  prefix?: string // "$", "~"
  suffix?: string // "+", "%", "K"
  separator?: string // thousand separator: " " or ","
  once?: boolean // animate only on first appearance
  className?: string
}

export function Counter({
  end,
  start = 0,
  duration = 2000,
  decimals = 0,
  prefix = '',
  suffix = '',
  separator = '',
  once = true,
  className = '',
}: CounterProps) {
  const containerRef = useRef<HTMLSpanElement>(null)
  const hasAnimated = useRef(false)
  const { value, run } = useCounterAnimation({
    start,
    end,
    duration,
    decimals,
    easing: easings.easeOutExpo,
  })

  useEffect(() => {
    const el = containerRef.current
    if (!el) return

    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          if (once && hasAnimated.current) return
          hasAnimated.current = true
          run()
          if (once) observer.unobserve(el)
        }
      },
      { threshold: 0.5 }
    )

    observer.observe(el)
    return () => observer.disconnect()
  }, []) // eslint-disable-line react-hooks/exhaustive-deps

  const formatted = separator
    ? value.toFixed(decimals).replace(/\B(?=(\d{3})+(?!\d))/g, separator)
    : value.toFixed(decimals)

  return (
    <span ref={containerRef} className={className}>
      {prefix}{formatted}{suffix}
    </span>
  )
}

Stats section

// components/StatsSection.tsx
import { Counter } from './Counter'

const stats = [
  {
    value: 1500,
    suffix: '+',
    label: 'Clients',
    duration: 2200,
  },
  {
    value: 99.9,
    suffix: '%',
    label: 'Uptime',
    decimals: 1,
    duration: 1800,
  },
  {
    value: 12,
    suffix: ' years',
    label: 'On the market',
    duration: 1500,
  },
  {
    value: 47,
    prefix: '~',
    suffix: ' countries',
    label: 'Geography',
    duration: 2000,
  },
]

export function StatsSection() {
  return (
    <section className="py-20 bg-gray-50">
      <div className="container mx-auto px-6">
        <div className="grid grid-cols-2 md:grid-cols-4 gap-8">
          {stats.map((stat) => (
            <div key={stat.label} className="text-center">
              <div className="text-5xl font-bold text-blue-600 mb-2">
                <Counter
                  end={stat.value}
                  suffix={stat.suffix}
                  prefix={stat.prefix}
                  decimals={stat.decimals ?? 0}
                  duration={stat.duration}
                  separator=" "
                />
              </div>
              <p className="text-gray-600 font-medium">{stat.label}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  )
}

Formatting: large numbers and locale

// utils/format-number.ts
export function formatNumber(
  value: number,
  options: Intl.NumberFormatOptions & { locale?: string } = {}
): string {
  const { locale = 'en-US', ...intlOptions } = options
  return new Intl.NumberFormat(locale, intlOptions).format(value)
}

// Usage in component:
// formatNumber(1500000, { notation: 'compact' }) → "1.5M"
// formatNumber(99.9, { minimumFractionDigits: 1 }) → "99.9"

How to choose the right easing function?

The choice of easing function depends on the desired effect. easeOut gives a smooth deceleration, easeOutExpo a sharp acceleration with fade-out. For statistics counters, cubic easeOut is usually used: it looks natural. If you want to emphasize growth, use easeOutExpo. Our hook's easings contain four basic functions that cover 90% of scenarios. For precise tuning, you can pass a custom function.

How we optimize performance: a case study

In one project, counters caused Layout Shift (CLS = 0.32) because numbers changed at different speeds and containers had no fixed width. We wrapped each counter in a <span> with min-width and added will-change: contents — CLS dropped to 0.01. Another common bug is hydration mismatch in Next.js, when the server renders 0 and the client shows 1500. Solution: use useEffect to start animation, not server-side render values. In the end, the client saved over 200 hours of development on self-experiments.

Problem Solution Benefit
Layout Shift (CLS) Fixed width, will-change CLS reduction from 0.32 to 0.01
Hydration mismatch Client-only start Errors eliminated
Recalculation on scroll IntersectionObserver with unobserve -70% calls

What's included in turnkey work

  1. Audit of existing counters (if any) — performance measurement, LCP, CLS.
  2. Development of a custom hook with support for easing, decimals, formatting.
  3. Integration of IntersectionObserver for lazy start.
  4. Documentation and export to npm package for reuse.
  5. Testing: unit tests for the hook (Jest + React Testing Library) and E2E tests (Cypress) on various devices.
  6. SSR/SSG support — correct server rendering without hydration.

How to avoid Layout Shift during counter animation?

The main cause of CLS is lack of reserved space for numbers. Use <span> with fixed width (e.g., min-width: 3ch) and will-change for browser hints. In our projects, this reduces CLS to 0.01 and requires no extra effort. If the stats section uses different number lengths, set min-width based on the maximum value.

Estimated timelines:

Stage Time
Analysis and prototype 2-4 hours
Development of hook and component 4-6 hours
Integration into project 2-4 hours
Testing and documentation 2-3 hours
Total 10 to 17 hours

The cost is calculated individually — it depends on the complexity of the section and the need for additional options (e.g., looped animation, RTL support). Contact us to get a consultation from an engineer with 10+ years of experience with React. We guarantee a test stand before integration.

Typical mistakes and how to avoid them

  • Counter doesn't start: make sure the element is visible (not display: none, not outside overflow:hidden).
  • Numbers jump on resize: use observer.unobserve() after first run to avoid restarting animation.
  • Lag on mobile: reduce animation duration to 1500 ms and use easeOut instead of complex functions.
  • React hydration: do not pass initial value via prop — let it be 0, and let the client start the animation.

Get an engineer consultation — we can help implement counters with performance guarantees.