react-countup vs react-spring
Animation and Counting Libraries in React
react-countupreact-springSimilar Packages:

Animation and Counting Libraries in React

In the realm of React development, libraries like react-countup and react-spring serve distinct yet complementary purposes. react-countup is specifically designed for creating animated number counting effects, making it ideal for displaying statistics, scores, or any numerical data that benefits from a dynamic presentation. On the other hand, react-spring is a powerful library for creating complex animations and transitions, leveraging the physics-based approach to provide smooth and natural motion in UI components. While react-countup focuses on a specific animation type (counting), react-spring offers a broader range of animation capabilities, allowing developers to create intricate animations that enhance user experience.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
react-countup02,08733.5 kB332 years agoMIT
react-spring029,0768.36 kB1356 months agoMIT

Feature Comparison: react-countup vs react-spring

Animation Type

  • react-countup:

    react-countup specializes in animating numerical values, providing a simple API to create smooth transitions from one number to another. It is particularly useful for displaying statistics or scores that change over time, offering options for duration, easing, and formatting.

  • react-spring:

    react-spring supports a wide range of animations, from simple transitions to complex physics-based animations. It allows developers to animate properties of components, such as position, scale, and opacity, providing a more dynamic and interactive user experience.

Ease of Use

  • react-countup:

    react-countup is designed for simplicity and ease of use. Developers can quickly implement counting animations with minimal setup, making it an excellent choice for those who need quick results without extensive configuration.

  • react-spring:

    react-spring has a steeper learning curve due to its extensive capabilities and flexibility. While it offers powerful features for creating complex animations, developers may need to invest time in understanding its API and concepts like springs and interpolations.

Performance

  • react-countup:

    react-countup is lightweight and optimized for performance, focusing solely on counting animations. It efficiently updates the DOM to reflect changes in numbers without causing unnecessary re-renders, making it suitable for performance-sensitive applications.

  • react-spring:

    react-spring is optimized for performance through its physics-based approach, which allows for smooth animations without janky movements. It intelligently manages animation frames and updates, ensuring that animations run smoothly even in complex UIs.

Customization

  • react-countup:

    react-countup provides basic customization options, such as duration, delay, and formatting of numbers. However, it is primarily focused on counting and may not offer extensive customization for other animation types.

  • react-spring:

    react-spring excels in customization, allowing developers to define various animation parameters, such as tension, friction, and damping. This flexibility enables the creation of highly tailored animations that fit the specific needs of the application.

Use Cases

  • react-countup:

    react-countup is ideal for use cases where numerical data needs to be highlighted, such as dashboards, statistics displays, or scoreboards. It is particularly effective in scenarios where quick visual feedback is essential to engage users.

  • react-spring:

    react-spring is suitable for a wide range of use cases, including transitions between pages, animated modals, and interactive UI elements. Its versatility makes it a go-to choice for developers looking to enhance the overall user experience with animations.

How to Choose: react-countup vs react-spring

  • react-countup:

    Choose react-countup if your primary goal is to display numerical data with engaging animations, such as counters or statistics that need to draw user attention. It is straightforward to implement and perfect for scenarios where you want to highlight changing numbers.

  • react-spring:

    Choose react-spring if you need a versatile animation library that can handle various types of animations, including transitions, gestures, and complex animations. It is suitable for projects that require a more comprehensive animation solution beyond simple counting.

README for react-countup

React CountUp

GitHub license Build Status Coverage Status Version Downloads Gzip size

A configurable React component wrapper around CountUp.js.

Click here to view on CodeSandbox.

Previous docs

react-countup

Table of Contents

Installation

yarn add react-countup

Usage

import CountUp from 'react-countup';

Simple example

<CountUp end={100} />

This will start a count up transition from 0 to 100 on render.

Render prop example

<CountUp
  start={-875.039}
  end={160527.012}
  duration={2.75}
  separator=" "
  decimals={4}
  decimal=","
  prefix="EUR "
  suffix=" left"
  onEnd={() => console.log('Ended! 👏')}
  onStart={() => console.log('Started! 💨')}
>
  {({ countUpRef, start }) => (
    <div>
      <span ref={countUpRef} />
      <button onClick={start}>Start</button>
    </div>
  )}
</CountUp>

The transition won't start on initial render as it needs to be triggered manually here.

Tip: If you need to start the render prop component immediately, you can set delay={0}.

More examples

Manually start with render prop

<CountUp start={0} end={100}>
  {({ countUpRef, start }) => (
    <div>
      <span ref={countUpRef} />
      <button onClick={start}>Start</button>
    </div>
  )}
</CountUp>

Autostart with render prop

Render start value but start transition on first render:

<CountUp start={0} end={100} delay={0}>
  {({ countUpRef }) => (
    <div>
      <span ref={countUpRef} />
    </div>
  )}
</CountUp>

Note that delay={0} will automatically start the count up.

Delay start

<CountUp delay={2} end={100} />

Hook

Simple example

import { useCountUp } from 'react-countup';

const SimpleHook = () => {
  useCountUp({ ref: 'counter', end: 1234567 });
  return <span id="counter" />;
};

Complete example

import { useCountUp } from 'react-countup';

const CompleteHook = () => {
  const countUpRef = React.useRef(null);
  const { start, pauseResume, reset, update } = useCountUp({
    ref: countUpRef,
    start: 0,
    end: 1234567,
    delay: 1000,
    duration: 5,
    onReset: () => console.log('Resetted!'),
    onUpdate: () => console.log('Updated!'),
    onPauseResume: () => console.log('Paused or resumed!'),
    onStart: ({ pauseResume }) => console.log(pauseResume),
    onEnd: ({ pauseResume }) => console.log(pauseResume),
  });
  return (
    <div>
      <div ref={countUpRef} />
      <button onClick={start}>Start</button>
      <button onClick={reset}>Reset</button>
      <button onClick={pauseResume}>Pause/Resume</button>
      <button onClick={() => update(2000)}>Update to 2000</button>
    </div>
  );
};

API

Props

className: string

CSS class name of the span element.

Note: This won't be applied when using CountUp with render props.

decimal: string

Specifies decimal character.

Default: .

decimals: number

Amount of decimals to display.

Default: 0

delay: number

Delay in seconds before starting the transition.

Default: null

Note: delay={0} will automatically start the count up.

duration: number

Duration in seconds.

Default: 2

end: number

Target value.

prefix: string

Static text before the transitioning value.

redraw: boolean

Forces count up transition on every component update.

Default: false

preserveValue: boolean

Save previously ended number to start every new animation from it.

Default: false

separator: string

Specifies character of thousands separator.

start: number

Initial value.

Default: 0

plugin: CountUpPlugin

Define plugin for alternate animations

startOnMount: boolean

Use for start counter on mount for hook usage.

Default: true

suffix: string

Static text after the transitioning value.

useEasing: boolean

Enables easing. Set to false for a linear transition.

Default: true

useGrouping: boolean

Enables grouping with separator.

Default: true

useIndianSeparators: boolean

Enables grouping using indian separation, f.e. 1,00,000 vs 100,000

Default: false

easingFn: (t: number, b: number, c: number, d: number) => number

Easing function. Click here for more details.

Default: easeInExpo

formattingFn: (value: number) => string

Function to customize the formatting of the number.

To prevent component from unnecessary updates this function should be memoized with useCallback

enableScrollSpy: boolean

Enables start animation when target is in view.

scrollSpyDelay: number

Delay (ms) after target comes into view

scrollSpyOnce: boolean

Run scroll spy only once

onEnd: ({ pauseResume, reset, start, update }) => void

Callback function on transition end.

onStart: ({ pauseResume, reset, update }) => void

Callback function on transition start.

onPauseResume: ({ reset, start, update }) => void

Callback function on pause or resume.

onReset: ({ pauseResume, start, update }) => void

Callback function on reset.

onUpdate: ({ pauseResume, reset, start }) => void

Callback function on update.

Render props

countUpRef: () => void

Ref to hook the countUp instance to

pauseResume: () => void

Pauses or resumes the transition

reset: () => void

Resets to initial value

start: () => void

Starts or restarts the transition

update: (newEnd: number?) => void

Updates transition to the new end value (if given)

Protips

Trigger of transition

By default, the animation is triggered if any of the following props has changed:

  • duration
  • end
  • start

If redraw is set to true your component will start the transition on every component update.

Run if in focus

You need to check if your counter in viewport, react-visibility-sensor can be used for this purpose.

import React from 'react';
import CountUp from 'react-countup';
import VisibilitySensor from 'react-visibility-sensor';
import './styles.css';

export default function App() {
  return (
    <div className="App">
      <div className="content" />
      <VisibilitySensor partialVisibility offset={{ bottom: 200 }}>
        {({ isVisible }) => (
          <div style={{ height: 100 }}>
            {isVisible ? <CountUp end={1000} /> : null}
          </div>
        )}
      </VisibilitySensor>
    </div>
  );
}

Note: For latest react-countup releases there are new options enableScrollSpy and scrollSpyDelay which enable scroll spy, so that as user scrolls to the target element, it begins counting animation automatically once it has scrolled into view.

import './styles.css';
import CountUp, { useCountUp } from 'react-countup';

export default function App() {
  useCountUp({
    ref: 'counter',
    end: 1234567,
    enableScrollSpy: true,
    scrollSpyDelay: 1000,
  });

  return (
    <div className="App">
      <div className="content" />
      <CountUp end={100} enableScrollSpy />
      <br />
      <span id="counter" />
    </div>
  );
}

Set accessibility properties for occupation period

You can use callback properties to control accessibility:

import React from 'react';
import CountUp, { useCountUp } from 'react-countup';

export default function App() {
  useCountUp({ ref: 'counter', end: 10, duration: 2 });
  const [loading, setLoading] = React.useState(false);

  const onStart = () => {
    setLoading(true);
  };

  const onEnd = () => {
    setLoading(false);
  };

  const containerProps = {
    'aria-busy': loading,
  };

  return (
    <>
      <CountUp
        end={123457}
        duration="3"
        onStart={onStart}
        onEnd={onEnd}
        containerProps={containerProps}
      />
      <div id="counter" aria-busy={loading} />
    </>
  );
}

Plugin usage

import { CountUp } from 'countup.js';
import { Odometer } from 'odometer_countup';

export default function App() {
  useCountUp({
    ref: 'counter',
    end: 1234567,
    enableScrollSpy: true,
    scrollSpyDelay: 1000,
    plugin: Odometer,
  });

  return (
    <div className="App">
      <span id="counter" />
    </div>
  );
}

License

MIT