How to Use React Spring

Posted on by Kyle Johnson | Updated:
Reading Time: 4 minutes

What is React Spring?

React Spring is an animation library that simplifies user interface (UI) animations. The animations have a natural look and feel due to their reliance on spring physics.

React Spring is unique because it takes a different approach than the more known techniques of keyframes, durations, and curves. If you have worked with transitions before, you may be familiar with the concepts of duration and easing curves, which determine the animation of changing different attributes. Specifically, a curve follows a set path and transitions in a specific timeframe.

A physical spring has its foundation in the concepts of mass, tension, and friction (among others). It is easy to observe how a physical spring moves when we change the weight that it carries or experiment with tighter or looser springs. The same is true for animations in React with Spring.

This tutorial will set up a React Spring project and then work through some React Spring examples.

Requirements

You should have already created a React app or have set up an online sandbox to follow this tutorial.

Installation

Install the React Spring library with the following yarn package manager (YPM) command.

yarn add react-spring

If you use an existing project that does not use YPM, install react-spring with the Node package manager (NPM).

npm install react-spring

With React Spring installed, you can now import components used in React Spring:

  • useSpring: Turns React Spring values into animated values.
  • animated: A library that animates outside React, handles the animated properties passed to it, and extends native React elements to receive animated values.
  • config: Properties provided to useSpring for configuration and tuning of Spring settings.

Here is a simple React Spring example that outputs the text: Hello springs!

import React from "react";
import { useSpring, animated, config } from "react-spring";
 
export default function App() {
   return <div className="App">Hello springs!</div>;

React Spring Example

Animating a Counter with InnerText

This React Spring example animates the innerText of an element to display a count of 5-star reviews. The component NumberReviews accepts a single property of count. This property will animate with a counter that counts up to the property when rendered.

When this code is compiled in your integrated development environment (IDE), you will notice that the transition between each value is not the same. Instead, each transition will gradually decrease the speed at which it changes.

import React from "react";
import { useSpring, animated, config } from "react-spring";
 
function NumberReviews({ count }) {
  const { number } = useSpring({
    from: { number: 0 },
    number: count,
    delay: 300,
    config: config.molasses
  });
 
  return <animated.span>{
    number.to((n) => n.toFixed(0))
  }</animated.span>;
}
 
export default function App() {
  return (
    <div className="App">
      5-Star Reviews: <NumberReviews count={448} />
    </div>
  );
}

Configuration: Mass, Tension, Friction

While the behavior of the counter is similar to an ease-out curve (a transition effect with a slow end) used in CSS transitions, the two techniques show space when modifying the configuration. For example, in the above React Spring example, the config property uses the preset of molasses.

The spring has a slow transition speed towards the end of the animation as if being dragged. The following configuration represents a combination of mass, tension, and friction and is the default for the config.molasses property. Updating these values changes how the spring behaves, allowing more control over the animation than a simple ease-out curve.

{
 mass: 1,
 tension: 280,
 friction: 120
}

Other preset configurations have a different feel, such as gentle, wobbly, and stiff. The following configurations are not wildly different or complex but have tweaked tension and friction.

{
   "gentle": { "tension": 120, "friction": 14 },
   "wobbly": { "tension": 180, "friction": 12 },
   "stiff": { "tension": 210, "friction": 20 },
   "molasses": { "tension": 280, "friction": 120 }
}

Use this syntax to update the configuration to get a feel for the differences. For example, notice how the vastly higher friction of the molasses configuration creates a dragging effect compared to stiff.

Interrupted Animations

Another thing to consider with animations, which React Spring gracefully manages, is the need to interrupt them in a user interface.

In the podcast Notes On Work, Caleb Porzio discusses the complexity of transitioning elements on the page, particularly when interrupting those transitions. Unfortunately, these user interactions are easily overlooked. Developers interact with elements as expected, while a typical user interacts with the software in unexpected ways.

Developers should account for the unexpected, including designing our animations to not complete. For example, an animated button click that resets the animation when repeatedly clicked. By default, each consecutive click of the button will stop the animation. By contrast, springs react to the consecutive clicks, which seems to behave as a single animation.

Using React Spring for Accessibility

When working with animations on the web, it is crucial to consider accessibility into how elements move on the page. For example, vertigo, nausea, or migraines affect many people, caused by animations on the web. Most operating systems have user preferences for reduced motion that aid in making web applications accessible.

Reduce motion in your React Spring project using react-reduced-motion. It is a cross-platform hook that allows disabling or lessening animations. We can import it into the example project using the following syntax near the top.

import { useReducedMotion } from "react-reduce-motion";

Conclusion

Springs are perhaps a more natural method by which to create animations for the web compared to the standard React methods. The configuration does not require an understanding of mathematical curves. It is comparatively easy to reason about the physics of a spring based on personal experience. If this technique feels more natural for you, consider using React Spring in your next project.

Liquid Web’s managed hosting options are a great fit for your next React Spring project. Contact our sales team to set up a server today.

Avatar for Kyle Johnson

About the Author: Kyle Johnson

Senior Developer @GiveWP (@LiquidWeb), formerly @NinjaForms. Afternoons are spent with my wife wrangling JSON, a black lab.

Latest Articles

Guide to Bare Metal Restore, Backup, & Recovery

Read Article

How to Upload Information to VMware through SFTP

Read Article

Accessing Man Pages on Ubuntu 16.04 LTS

Read Article

Premium Business Email Pricing FAQ

Read Article

Microsoft Exchange Server Security Update

Read Article