Type to generate custom UI components with AI

Type to generate UI components from text

OR

Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.

Explore Components

How to Make Animated React Apps with React Spring

Animation has become an essential part of modern web design and development. It can greatly enhance user experience by improving engagement, conveying information clearly, and establishing seamless workflows. However, crafting beautiful yet complex animations can be challenging using traditional CSS and JavaScript. This is where you need animation libraries and that is where React Spring shines.

The principle you will be working with is called a spring, it does not have a defined curve or a set duration. In that it differs greatly from the animation you are probably used to. We think of animation in terms of time and curves, but that in itself causes most of the struggle we face when trying to make elements on the screen move naturally, because nothing in the real world moves like that. In React Spring, a spring simply animates values from one state to another. Updates are accumulative, springs remember all the values you ever pass. You can use arbitrary names. –  React Spring docs

Build animations with React Spring

The Importance of Adding Animation to Your Web Application

The importance of animation in modern web applications cannot be overstated. Small animations provide users with visual cues that communicate relationships and hierarchies between elements. More advanced animations can capture attention, direct focus, and even evoke emotions. Users have come to expect subtle animations that indicate loading, status changes, and responses to interactions.

Animation can significantly elevate the user experience of a web application when implemented purposefully. Subtle animations guide the user’s attention to important elements, provide visual feedback, and create continuity between application states. Without animation, transitions between pages or interactions can feel disjointed and hard to follow.

Thoughtfully designed animations enhance comprehension of the interface flow while making the experience more visually stimulating. Loading animations, micro-interactions, and transitions all contribute to a sense of polish and responsiveness. This results in higher audience engagement and retention as users connect with the personality of the animated interfaces.

More Importance of Animations

Beyond usability, animation brings applications to life uniquely and memorably. The ability to delight users and create an emotional connection is invaluable in this crowded digital landscape. Animation provides a competitive edge that makes your application stand out. With so many benefits for usability, engagement, and branding, animation should be a priority rather than an afterthought in modern web development. Taking the time to animate core interactions and transitions will greatly improve how your users experience your application.

In this article, we will explore the fundamentals of React Spring and techniques for crafting beautiful, high-performance animations that elevate modern web experiences. React Spring provides the tools to overcome animation complexities and deliver the dynamic interfaces your users will love.

What is React Spring?

React Spring is a physics-based animation library that makes creating natural, high-performance animations in React straightforward. It is a cross platform spring physics. Its API exposes a set of hooks like useSpring, useTrail, and useTransition that abstract away the underlying animation mechanics. This allows developers to focus on declarative animation components rather than imperative step-by-step animations.

React Spring is a library for building interactive, data-driven, and animated UI components. It can animate HTML, SVG, Native Elements, Three.js, and more.

React Spring docs

React Spring homepage

The React Spring library delivers the capabilities needed for you to meet your web or mobile application’s user experience expectations.

Its physics-based animations behave realistically without hard-coding durations and easing curves. The performance focus means complex animated interfaces can render smoothly at even 60fps. React Spring offers the right abstractions so developers can focus on declarative components rather than animation intricacies.

Check out this video explaining Why React Spring is a physics-based animation:

What is React Spring Used For?

React Spring is a physics-based animation library used to create smooth, fluid interactivity, natural animations and transitions in React apps. It provides several hooks like useSpring, useSprings, useTrail, useTransition, and useChain to animate different UI elements.

In the following sections of this article, I will walk you through using these hooks to create stunning, beautiful, and captivating user interfaces for your web applications with React.

Before we delve further, let me quickly introduce you to Purecode AI

Purecode AI is an innovative AI assistant that can generate thousands of custom HTML, CSS, and JavaScript components for web development. It provides an extensive library of responsive, pre-made components that come with default styling out of the box. You can easily customize these components by tweaking colors, spacing, paddings, and more to match their brand design needs.

The key advantage of Purecode AI is its ability to generate not just the component markup, but also the accompanying CSS styles and JavaScript interactivity required to build fully-functional components. This saves you an immense amount of time compared to starting from scratch. With its intelligent AI assistant and vast component library, Purecode AI is the future of efficient, customizable web development.

Purecode AI homepage

Prerequisites

Before diving into React Spring, there are a few requirements to ensure you can properly follow along:

NodeJS and NPM

Since React Spring is available as an npm package, you will need Node.js and npm installed to bring it into your projects. Make sure you have Node.js version 6 or higher installed. This will come bundled with npm, the Node package manager needed to install React Spring.

Basic Understanding of React

React Spring builds on top of React and is designed to work within React components and hooks. Having a solid grasp of React fundamentals like components, props, state, and hooks will be important before using React Spring. You should understand topics like:

  • Creating React components with ES6 classes or functions

  • Passing props to components

  • Managing state with the useState hook

  • Using effects with the useEffect hook

Even if you are still mastering React, you should be comfortable with these core concepts before adding React Spring.

If you need a refresher on using React, check out this YouTube video below:

Understanding React Hooks

Along with React fundamentals, a basic understanding of React hooks will be very beneficial for using React Spring. React Spring provides hooks like useSpring and useTransition rather than React components. You will need to understand how to use and chain together these custom hooks within your components.

So make sure you are comfortable with topics like:

  • Creating custom hooks

  • Calling hooks from React components

  • Chaining hook calls together

  • Properly handling hook dependencies

With this foundation in React and Hooks, you will be well prepared to start animating with React Spring!

If you are excited as much as I am writing this article, then let’s dive right in 🚀

Setting Up a React App

In your terminal, enter the following command to create a new React application:

npx create-react-app my-app && cd my-app

Once your app is set up, run the application by entering either of these commands in your terminal:

yarn start

Or using npm:

npm start

Your server should launch in your browser at http://localhost:3000/, as shown below:

React app

How to Install React Spring

To add React Spring to your React or React Native application, you can use either of these package managers; Yarn or NPM. Simply open a terminal window on your project’s root directory and run the installation command below:

npm install @react-spring/web

Or

yarn add @react-spring/web

This makes the React Spring animation library available in your application.

React Spring Hooks Overview

Given the introduction of Hooks in React from v.16.8.0, you can now add state to functional components in React applications. The React Spring library leverages this to provide you with different ways to create animated components.

React Spring provides several powerful hooks for creating different types of animations in React. In the following sections, we will examine some key hooks and their use cases.

1. The useSpring Hook

The useSpring hook is used for single-element animations that transition between two states. For example:


import { useSpring, animated } from '@react-spring/web';

const animation = useSpring({
  opacity: 1,
  from: { opacity: 0 }
})

return <animated.div style={animation}>I will fade in!</animated.div>

Here useSpring will transition the opacity from 0 to 1, creating a fade-in effect. We pass the animated values to the animated.div.

The complete code will then be:

import "/index.css";
import { animated, useSpring } from "@react-spring/web";

export default function () {
  const [props, api] = useSpring(
    () => ({
      from: { opacity: 0 },
      to: { opacity: 1 },
    }),
    []
  );

  return (
    <animated.div className="spring-box" style={props}>
      I will fade in!
    </animated.div>
  );
}
useSpring demo

2. The useSprings Hook

useSprings is useful for animating multiple elements in a list. If you want to orchestrate multiple springs with a unified API, this is probably the best hook for you.

useSprings differs because we supply the number of springs we want and then pass our configuration, whether you’re using a function or not. We can configure each animation based on the list index:

import "/index.css";
import { animated, useSprings } from "@react-spring/web";

export default function () {
  const numberItems = 4;
  const [springs, api] = useSprings(
    numberItems,
    () => ({
      from: { opacity: 0 },
      to: { opacity: 1 },
    }),
    []
  );

  return (
    <div>
      {springs.map((props) => (
        <animated.div className="spring-box" style={props}>
          Hello World
        </animated.div>
      ))}
    </div>
  );
}
useSprings - demo

3. The useTrail Hook

The useTrail hook creates an animated trail effect by chaining animations with a delay. it has an identical API signature to useSprings the difference is the hook automatically orchestrates the springs to stagger one after the other.

import "/index.css";
import { animated, useTrail } from "@react-spring/web";

export default function () {
  const numberItems = 4;
  const trails = useTrail(numberItems, {
    from: { opacity: 0 },
    to: { opacity: 1 },
  });

  return (
    <div>
      {trails.map((props) => (
        <animated.div className="spring-box" style={props}>
          Trailing
        </animated.div>
      ))}
    </div>
  );
}

Each item will drop down and fade in sequentially for a trail effect.

useTrail - demo

4. The useTransition Hook

We can use useTransition for animating items as they mount and unmount. It is best suited for animating in and out datasets or items you don’t particularly want to be left in the DOM, e.g. a dialog.

The useTransition hook depends on an array of data. That data can be anything you want, we use a lot of internals to track each datum including inferring the keys, this is the first argument. A second is a config object, which is different from useSpring or useSprings.

import "/index.css";
import { animated, useTransition } from "@react-spring/web";

export default function () {
  const data = ["Trans", "itio", "ning"];

  const transitions = useTransition(data, {
    from: { opacity: 0 },
    enter: { opacity: 1 },
    leave: { opacity: 1 },
  });

  return transitions((style, item) => (
    <animated.div className="spring-box" style={style}>
      {item}
    </animated.div>
  ));
}

As items are added/removed from items, they will fade in and out.

useTransition - demo

5. The useChain Hook

useChain allows sequencing animations. useChain is used to orchestrate animation hooks in sequence with one another.

This is best used when you specifically want to orchestrate different types of animation hook e.g. useSpring and useTransition in sequence as opposed to multiple useSpring hooks where you could either use useSprings or create an async animation.

This will first run the useSpring hook and then the useTransition hook when the component has mounted and the useSpring has come to rest.


import "/index.css";
import {
  useTransition,
  useSpring,
  useChain,
  animated,
  useSpringRef,
} from "@react-spring/web";

export default function () {
  const data = ["Trans", "itio", "ning"];

  const springRef = useSpringRef();
  const springs = useSpring({
    ref: springRef,
    from: { size: "20%" },
    to: { size: "50%" },
  });

  const transRef = useSpringRef();
  const transitions = useTransition(data, {
    ref: transRef,
    from: { scale: 0 },
    enter: { scale: 1 },
    leave: { scale: 0 },
  });

  useChain([springRef, transRef]);

  return (
    <animated.div
      style={{
        height: springs.size,
        width: springs.size,
        background: "#96f",
      }}
    >
      {transitions((style, item) => (
        <animated.div
          style={{
            ...style,
          }}
          className="spring-box"
        >
          {item}
        </animated.div>
      ))}
    </animated.div>
  );
}

Now the spring animation will run first, followed by the trail.

useChain - demo

Practical Examples

Let’s look at some practical use cases for React Spring hooks.

1. Cards List – useSprings

The useSprings hook is great for animating lists of elements like cards:

const springs = useSprings(cards.length, i => ({
  // animate each card based on the index
}))

return springs.map(style => (
  <AnimatedCard style={style}>...</AnimatedCard>
))

We can stagger the animations or bounce the cards on hover.

2. Image Gallery – useChain

For an image gallery, useChain allows us to orchestrate animations:

const fade = useSpring({...})
const zoom = useSpring({...})

useChain(fade, zoom)

return (
  <animated.img style={fade}>
  <animated.div style={zoom}>
)

Now the image fades in first, followed by the zoom effect.

3. useSpring + Loop

We can create seamless looping animations with useSpring:

const props = useSpring({
  loop: true,
  from: { x: 0 },
  to: { x: 100 }
})

return <animated.div style={props} />

The loop config restarts the animation automatically.

How React Spring Works

React Spring depends on two core concepts – SpringValues and animated components. Let’s explore animated components.

An animated component receives SpringValues through the style prop and updates the element without causing a React render. It works because it is a Higher Order Component (HOC) mapped to a dictionary of elements based on the target you select. This allows passing props for your app while containing the logic to interpolate the SpringValues from the hook used.

You can import animated from any React Spring target. However, an animated component is specific to that target since they use native elements. For example, @react-spring/web has access to web elements like div, while @react-spring/three can animate three.js elements.

// ✅ Works for web
import { animated } from '@react-spring/web'
<animated.div />

// ❌ Won't work for three.js
import { animated } from '@react-spring/three'
<animated.mesh />

While animating elements is useful, you will typically want to style them too. React Spring works with any styling technique like CSS Modules or Tailwind since animated components accept native element props like className.

You can also compose animated components with css-in-js libraries:

import { styled } from '@stitches/react'

const AnimatedModal = styled(animated.div, {
  width: '40vw',
  height: '20vh',
  // ...
})

For components from other libraries, wrap them with animated since it is an HOC:

// ExternalComponent from another library

const AnimatedDialog = animated(ExternalComponent)

This allows animating as long as the wrapped component passes style to the native element.

FAQs

What Is the Difference Between useSpring and useTransition?

  • useSpring is used for single-element animations that change state from A to B.

  • useTransition is used for animations on the mount/unmount of list elements. It handles entering, leaving, and updating of elements.

How Does React Spring Work?

React Spring calculates the animation mechanics like velocity, friction, etc behind the scenes to produce natural motions. It exposes a simple API to configure the animations as needed.

What is the Best Backend for React?

Some popular backend choices for React are:

  • Node/Express for a JavaScript stack

  • Spring Boot for Java/JVM stack

  • Django/Flask for Python stack

  • Ruby on Rails for Ruby stack

Ultimately the backend choice depends on factors like experience, use cases, scalability needs, etc.

Can We Use React With Spring Boot?

Yes, React and Spring Boot work very well together. React can be used for building the front-end UI while Spring Boot handles the back-end API and business logic. This provides a clean separation of concerns. Check out this article on how to integrate React Spring Boot in your application

Table on Key Aspects of Making Animated React Apps with React Spring

React SpringFramer MotionReact Transition Group
ApproachPhysics-based animationMotion and gesture libraryTransition stages and DOM manipulation
Animation CapabilitiesSpring animations, staggered animations, transitionsDrag, layout animations, gesturesCSS transitions and animations
Learning CurveModerateEasy to ModerateEasy
PerformanceGoodVery GoodGood
Community SupportModerateStrongStrong
CustomizationHighly CustomizableHighly CustomizableLimited Customization
Extra FeaturesGesture support with use-gestureAdvanced gesture support, variantsN/A

What You Have Learned

In this article, I walked you through an introduction to using React Spring for creating animations in React apps. You now understand the core hooks React Spring provides like useSpring, useSprings, useTrail, useChain, and useTransition for creating different animation effects.

The code examples have shown you how to configure physics-based animations using these hooks for elements like cards, image galleries, and menus. You’ve seen techniques for choreographing sequenced animations with useChain and creating looping effects with useSpring.

Further Readings

If you enjoyed reading this piece, do take a look at other great articles from our blog:

If you want to learn more, do check out this video tutorial on implementing animations with React Spring:

Emmanuel Uchenna

Emmanuel Uchenna

Emmanuel is an experienced and enthusiastic software developer and technical writer with 4+ proven years of professional experience. He focuses on full-stack web development. He is fluent in React, TypeScript, VueJS, and NodeJS and familiar with industry-standard technologies such as version control, headless CMS, and JAMstack. He is passionate about knowledge sharing.