Skip to content

Instantly share code, notes, and snippets.

@Eunit99
Last active June 30, 2022 10:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Eunit99/db4cbe73262dc0dab99332dea6d88b78 to your computer and use it in GitHub Desktop.
Save Eunit99/db4cbe73262dc0dab99332dea6d88b78 to your computer and use it in GitHub Desktop.
React Spring

Introducing React Spring as an animation library: Walk-throughs and examples

Introducing animations in web development

banner

Website design and development experienced tremendous changes, improvements, and disruptive innovations from when it was just a single static page to what it is today - unique, slick, and beautiful. Web developers use animations for breathing life and motion into static website layouts. They make the user experience more intuitive and exciting. Animations on website turn an ordinary user experience into an unforgettable journey that ends up amazing. Web animations is translated via movements, adventures, interactions, and with colors changes.

Animation happens when something created in still or two-dimensional form is “brought to life” and appears to move in a way that follows laws of physics. It’s the way a cartoon character walks across the screen or how an app icon bounces like a ball while it is loading on the desktop [...] - DesignHack

Introducing React Spring as an animation Library

React Spring is a spring-physics based animation library that should cover most of your UI related animation needs. It gives you tools flexible enough to confidently cast your ideas into moving interfaces. This library represents a modern approach to animation.

react spring image

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

Pros of using animations on your website

  • Animations enhance design
  • Animations showcase uniqueness of a website
  • Establish a better or stronger emotional connection
  • Animations improve engagement and conversion
  • Improve the overall user experience

In this tutorial, I shall walk you through using React Spring library to provide awesome animations to your CRA (React App).

Prerequisites to setup your CRA

Before you proceed with this tutorial, you must satisfy the following conditions:

  1. Node.js ≥v6 is installed on your local machine
  2. NPM is installed on your local machine
  3. You have an understanding of React.js
  4. You have an understanding of React hooks
  5. You are interested in wowing your users

Let us jump right in 🎇🎆🎉

dancing panda

Getting Started with React Spring

I will recommend that you add React Spring to your application via 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

Or

yarn add react-spring

This makes React Spring available in your application.

React Spring 5 hooks explained

React Hooks make it feasible to add state to functional components.

thinking gif

React Spring takes this up a notch by providing a hook-based API which allows you to define and convert data that you would generally pass as props to animated data.

To better demonstrate some of the features of React Spring, let us take a closer look at the available hooks in the React-spring module. There are five major hooks available in React Spring at the moment:

  • useSpring — A single spring moves data from a to b

  • useSprings — Multiple springs mainly for lists, where each spring moves data from a to b

  • useTrail — Multiple springs with a single data set, one spring follows or trails behind the other.

  • useTransition — For mount/unmount transitions (lists where items are added/removed/updated)

  • useChain — To queue or chain multiple animations together For each of these hooks, there are several animation effects you can implement, it is limitless and goes as far as your imagination will take you.

I will walk you through some use cases for useSpring , useSprings, useTrail, useTransition, and finally, useChain to demonstrate how you can implement them in your React applications.

React Spring Examples: Using useSpring in your React app

First, you fetch your imports

import { useSpring, animated } from 'react-spring'

useSpring is one of the simplest React Spring hooks that you can you to quickly add animations to your app. The useSpring hook accepts two props minimum; which are from and to which are part of the reserved keywords. It simply animates values from one state to another. useSpring converts defined values into animated values; it allows animating the state changes from the initial from to the final to. A spring simply animates values from one state to another. Updates are accumulative, springs remember all the values you ever pass. Learn more about the useSpring hook here..

Example:

import { useSpring, animated } from 'react-spring'

function App() {
  const props = useSpring({ to: { opacity: 1 }, from: { opacity: 0 } })
  return <animated.div style={props}>I will fade in</animated.div>
}

You need the animation-primitive itself, and a special factory called animated. This library animates outside React (for performance reasons). Your view has to know how to handle the animated props you pass to it. This is what animated is there for, it extends native elements to receive animated values.

<iframe src="https://codesandbox.io/embed/ov3r2oojyy?fontsize=14&view=split" style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;" allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts" ></iframe>

React Spring Examples: Using useSprings in your React app

First, you fetch your imports

import { useSprings, animated } from 'react-spring'

useSprings is just like useSpring. It allows you to create multiple springs, each with its own config. It is used for static lists where each spring moves data from an initial state to a final state. This also provides you with two options on how to implement it. Since you are working with multiple values, this method works in two forms which are:

Either: overwrite values to change the animation

If you re-render the component with changed props, the animation will update.

const springs = useSprings(
  number,
  items.map(item => ({ opacity: item.opacity }))

Or: pass a function that returns values and updates using the API

You will get an updater function back, and it won't cause the component to render like an overwrite. Handling updates like this is useful for fast-occurring updates, but you should prefer it.Optionally there's a stop function.

const [springs, api] = useSprings(number, index => ({ opacity: 1 }))

// Update springs with new props
api.start(index => ({ opacity: 0 }))
// Stop all springs
api.stop()

Finally: distribute animated props among the view

The return value is an array containing animated props

return springs.map(styles => <animated.div style={styles} />)
<iframe src="https://codesandbox.io/embed/r5qmj8m6lq?fontsize=14&view=split" style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;" allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts" ></iframe>

React Spring Examples: Using useTrail in your React app

First, you fetch your imports

import { useTrail, animated } from 'react-spring'

The useTrail hook enables you to create multiple springs with a single config. It shares almost the same configuration with the useSpring hook with a variation in the implementation. It animates the first item of a list of elements while the rest of the elements form a natural trail and follow their previous sibling to animate.

Example

const items = [
  { text: "ITEM1", id: 1 },
  { text: "ITEM2", id: 2 },
  { text: "ITEM3", id: 3 },
  { text: "ITEM4", id: 4 }
];
export default function App() {
  const trail = useTrail(items.length, { opacity: 1, from: { opacity: 0 } });
  return (
    <>
      {trail.map((props, i) => (
        <animated.div style={props} key={i}>
          {items[i].text}
        </animated.div>
      ))}
    </>
  );
}

Let us break this code down

This argument is the number of animation style objects to create.

const items = [
  { text: "ITEM1", id: 1 },
  { text: "ITEM2", id: 2 },
  { text: "ITEM3", id: 3 },
  { text: "ITEM4", id: 4 }
];

This argument below is the animation style to create.

 const trail = useTrail(items.length, { opacity: 1, from: { opacity: 0 } });

Then we can apply them as we do with the useSprings hook.

{trail.map((props, i) => (
        <animated.div style={props} key={i}>
          {items[i].text}
        </animated.div>
))}
<iframe src="https://codesandbox.io/embed/usetrail-demo-49jsc?fontsize=14&view=split" style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;" allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts" ></iframe>

React Spring Examples: Using useTransition in your React app

First, you fetch your imports.

import { useTransition, animated } from 'react-spring'
function TransitionArray() {
  const [items, setItems] = useState(NUM_TRANS)

  const transitions = useTransition(items, {
    from: { opacity: 0 },
    enter: { opacity: 1 },
    leave: { opacity: 0 },
    delay: 200,
    config: config.molasses,
    onRest: () => setItems([]),
  })

  useEffect(() => {
    if (items.length === 0) {
      setTimeout(() => {
        setItems(NUM_TRANS)
      }, 2000)
    }
  }, [items])

  return (
    <div style={{ display: 'flex' }}>
      {transitions(({ opacity }, item) => (
        <animated.div
          style={{
            opacity: opacity.to(item.op),
            transform: opacity
              .to(item.trans)
              .to(y => `translate3d(0,${y}px,0)`),
          }}>
          {item.fig}
        </animated.div>
      ))}
    </div>
  )
}

useTransition allows you to create an animated transition group. It takes in the elements of the list, their keys, and lifecycles. The animation is triggered by the appearance and disappearance of the elements. You can use transition for arrays, to toggle between components, or for mounting/unmounting of the same component. Learn more about the useTransition hook here

<iframe src="https://codesandbox.io/s/react-spring-v9-usetransition-zjt3q?fontsize=14&view=split" style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;" allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts" ></iframe>

React Spring Examples: Using useChain in your React app

First, you fetch your imports

import { useChain, animated, } from 'react-spring'

useChain allows you to set the execution sequence of previously defined animation hooks. To do this, you need to use refs, which will subsequently prevent the independent execution of the animation.

Learn more about the useChain hook here

<iframe src="https://codesandbox.io/s/react-spring-usechain-l07f8?fontsize=14&view=split" style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;" allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts" ></iframe>

Difference between Spring Boot and React Spring and NodeJS

spring boot image

  • Spring boot is an open source Java-based framework used to create a micro Service. It is developed by Pivotal Team and is used to build stand-alone and production ready spring applications. More information about React Spring boot here.

whereas

react spring image

  • React Spring is a spring-physics based animation library that should cover most of your UI related animation needs. It gives you flexible tools to cast your ideas into moving interfaces confidently. More information here.

whereas

image

  • Node.js is an open-source, cross-platform, back-end JavaScript runtime environment that runs on the V8 engine and executes JavaScript code outside a web browser, which was designed to build scalable network applications. Node.js lets developers use JavaScript to write command line tools and for server-side scripting—running scripts server-side to produce dynamic web page content before the page is sent to the user's web browser.

How to Create a Timer with React Spring

In this tutorial, you shall be walked through using React Spring to create a timer. This will be a pretty straight forward app. Let us dive right in.

glass

First create a React project

npx create-react-app timer-app

Change directory into timer-app

cd timer-app

Install React Spring package

npm install react-spring

React Spring is used to add spring-based animations to our app. In this React Spring example, we will use the React Spring useSpring hook to demonstrate this example.

Let us now proceed to create the timer in React.JS.

Add the following lines of code in your App.js:

import React, { useState } from "react";
import { useSpring, animated } from "react-spring";

export default function AnimateTimer() {
   const [flip, set] = useState(false);
   const { number } = useSpring({
      reset: true,
      reverse: flip,
      from: { number: 0 },
      number: 60,
      delay: 100,
      onRest: () => set(!flip),
   });
   return <animated.div>{number.to((n) => n.toFixed(2))}</animated.div>;
}
export default function App() {
   return (
      <div style={{ marginLeft: 500, marginTop: 200 }}>
         <AnimateTimer />
      </div>
   );
}

Congratulations

Explanation of the different parts of our code

  • The React Spring example creates a spring object, which will count from 0 to 60.

  • Then we added the attribute reset to start the loop; it is set to true,

  • we added the attribute reverse to indicate when the counting should start or end,

  • we added the attribute delay to delay the animation,

  • we added the attribute onRest to indicate what to do when the counting stops.

  • we added the attribute n.toFixed(2) indicates how many digits to show after the decimal.

Output

Timer example

Congratulations

The performance advantages of React Spring

  • React spring animations are based on physics. There is no need to customize duration or easing. The result is smooth, soft, and natural-looking animations.

  • Easy-to-use and clear documentation.

  • A lot of interesting and beautiful demos in the documentation and on the React Spring creator Paul Henschel’s CodeSandbox page.

  • The library repository is continually being updated and maintained. A small, but quite active community (spectrum, discord) has formed around the library. Paul Henschel regularly shares interesting insights, demos, and more on his Twitter page.

React Spring Alternatives

  • Framer/motion: A production-ready motion library for React. Utilize the power behind Framer, the best prototyping tool for teams—proudly open source.

  • React Transition Group: React Transition Group exposes transition stages, manages classes and group elements, and manipulates the DOM in useful ways, implementing actual visual transitions much more effortless. The React Transition Group component was developed by the ReactJS community team. It allows you to implement basic CSS animations and transitions worry-free.

  • React GSAP: This library lets you use the GreenSock Animation Platform (GSAP) in React in a fully declarative way. It abstracts away the direct use of the GSAP Tween and Timeline functions. If you’d like to learn about GSAP tutorials for beginners, pick into our standalone article on the topic.

Conclusion

In this tutorial, I walked you through animations in web development, introduced you to React Spring and its 5 hooks.

thinking gif

Video on implementing animations with React-Spring

Implementing animations with React-Spring

Further readings

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment