HomeBlogWeb DevelopmentReact Spring - Getting the Most Out of React Animation Library

React Spring - Getting the Most Out of React Animation Library

Published
13th Sep, 2023
Views
view count loader
Read it in
12 Mins
In this article
    React Spring - Getting the Most Out of React Animation Library

    The world of animation has come a very long way. Now it’s become necessary for a website to have some kind of animations to increase user interaction. It reduces the mechanical feel of a website or an app, giving it a much more natural feel.

    But we only have one way of adding animations to our app, and that is by writing a bunch of CSS, which is not a very wise decision when it comes to React. As React is all about making the code simpler by focusing on the DRY principle, and if still we add a bunch of CSS in our app which may be simpler but are hardcoded everywhere, it violates that principle which is the reason for React’s popularity.

    React is a very simple but powerful JS library in which we can do pretty anything like adding animations with just a couple of lines of code, as we will see in this blog, check out the React JS learning path and get a structured learning and understanding path of React JS which can be pretty confusing for the beginners.

    And honestly, CSS isn’t enough for all types of animation that we as front-end developers want our website or app to have, like popup, transition groups, increasing or decreasing, or having a ton of animation going on and off simultaneously.

    To solve this problem only, we have animation libraries that have made our work easier as with just a few lines of code, we can create an animation that we want our website or app to have.

    There are tons of libraries out there, React-Spring, Framer-Motion, React Transition Group, React Motion, etc., but in this blog, we will only be focussing on a single animation library - React Spring.

    As told above, in this blog, we will be discussing the React Spring library but not in detail. We will cover only the basics of React Spring-like how and why, and other cool stuff so that you can start creating your animation after reading this blog.

    Let’s start…

    What is React Spring 

    According to the React-Spring documentation, “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.”

    What it means is that React Spring is an animation library that allows us to make or create smooth fluid-like animations which can be customized into transitions without a strict path to follow but will have a from value and a top value for the animation to look like one or else it will again give us those mechanical vibes.

    React Spring can also be considered a modern solution to all our animation problems as it is made keeping in mind the advantages and disadvantages of the two most popular animation libraries React Motion and Animated.

    Why React Spring

    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.

    Think of it as a spring, when we pull a spring and release it, all that build-up tension gets released and we see a natural wave motion that comes to a smooth stop when all that tension is released from it. 

    In React Spring, durations are of no use as it doesn’t work that way. It works on real-life world examples or simply physics properties like tension we discussed above, intensity, speed, initial velocity, and many other physical metrics of an element's movement to shape the way we want the animation to behave.

    While there are tons of animation libraries out there as discussed above, they all have their different and unique approaches to making animations and among all of them React Spring has the best approach as it doesn’t work on CSS classes and Render Props, it rather works on API in which writing and managing code are easy and its documentation is full of examples and explanations which can help us start making our animations in no time.

    So, what are we waiting for, let's dive into the world of animations?

    Getting Started

    Before we move ahead and start discussing the how part of our blog, certain conditions are mandatory and should be fulfilled.

    1. It is by default assumed that we have at least the basic knowledge of reacting and react hooks. If not, check out our React JS learning path to get started with React.
    2. As it supports only hooks, there is no way to use this library in a class-based React component.

    React-Spring library provides two APIs, the Hooks API, and the Render-Props API. For this blog, we will only focus on the Hooks API, and that too a single hook which is the basic hook. The basic approach for all the hooks is the same except for their use and which we will understand from practice.

    But fear not, all the concepts from the Hooks API transfer to the Render-Props API very nicely.

    Setting Up React Spring

    The best way to add React Spring to our application will be via the package managers. Simply open the terminal window of the project’s root directory and run the installation command below:

    npm install react-spring

    #OR

    yarn add react-spring

    This makes React Spring widely available in our application for later use.

    While we were working on some projects for this blog to show what exactly React Spring is capable of with some very basic examples, we ran into some major problems and wish to tell you the problem and its solution.

    The problem was as soon as we applied the hook given to us by the React Spring, we received an error as shown below.

    React Spring Problem

    The problem was that our App had two React in its tree clashing with each other as we applied the React Spring hook.

    There are two ways in which we can solve this problem.

    1. The first method is according to the React documentation is to remove the duplicate React by, running the following command -  

    npm link ../myapp/node_modules/react

    2. The second method is the method that we used, we just removed one of the two Reacts from our App. We chose the React that was in React-spring / node_modules / react as it will have a lesser impact than removing the actual React from node_modules.

    Again it's up to you to choose which method to go with.

    React Spring Hooks

    Well as we have already discussed above, React Spring works on API one of which contains five different hooks for us to explore and make our custom animations with.

    1. useSpring - Used for moving elements from one point to another
    2. useSprings - moving multiple elements in a single step each containing the useSpring hook
    3. useTrail - Multiple springs with a single data set, one spring follows or trails behind the other.
    4. useTransition -  used when items are added or removed, it will animate these changes.
    5. useChain - to start and end animations in a sequence.

    But for this blog, we will only be focussing on the useSpring hook as again it is the basic hook, and understanding it is crucial.

    React Spring has a Cross-Browser and Cross-Platform compatibility which means that it can be used to make apps and websites for any kind of web and platforms like android, and ios using React Native, multidimensional arrays, and animations like Three.JS. Konva, etc

    @react-spring/konva
    @react-spring/native
    @react-spring/three
    @react-spring/web
    @react-spring/zdog

    Well, at a first glance they all look like they have tons of properties which will result in a different animation with different effects altogether but that is not the case.

    They are all interlinked and have a special characteristic that only they can offer in the animation other than that they are all the same with the same basic concepts.

    We will cover all those basic concepts with an example to make them easier to understand.

    useSpring Hook

    It is the simplest and most basic hook that React Spring has to offer, and it mainly focuses on turning the defined values into animated ones.

    We can animate our app using this hook in two ways -  

    1. Overwriting the existing react props with the different sets of props on component re-renders.

    const styles = useSpring({ opacity: toggle ? 1 : 0 });

    2. Using an updater function that returns some values different from that we have sent to the function and updates the values using an API.

    According to the documentation, this method is faster as it avoids re-rendering of the component like the first method and should be generally used.

    const [styles, api] = useSpring(() => ({ opacity: 1 }));
    // Update spring with new props
    api.start({ opacity: toggle ? 1 : 0 });
    // Stop animation
    api.stop();
    return <animated.div style={styles}>i will fade</animated.div>;

    For understanding this hook, we will be making components and applying a useSpring hook with different use cases.

    Understanding Different Properties and Use Cases of useSpring Hook

    Before moving forward, we have to see the working of the useSpring hook with a practical example to understand the hook better.

    For that, we will be creating a basic app in which we have a text field and we will apply different animations to it.  

    The basic structure of the app is as follows -

    import React, { useState } from "react";
    const Simple_Example = () => {
      const [flip, setFlip] = useState("false");
      return (
        <>
          <h1>hello</h1>;
          <button onClick={() => setFlip(!flip)}>Click</button>
        </>
      );
    };
    export default Simple_Example;

    Let's add the hook and fill this boring text with color animation.

    import React, { useState } from "react";
    import { useSpring, animated } from "react-spring"; //importing useSpring and animated
    const Simple_Example = () => {
      const [flip, setFlip] = useState("false");
      const props = useSpring({//applying hooks
        from: {color: "blue"},
        to: {color: "red},
      });
     return (
        <>
        {/* Applying the props style in the style tag as shown below
        And wrapping our h tag with the animated tag as shown */}
          <animated.h1 style={props}>hello</animated.h1>
          <button onClick={() => setFlip(!flip)}>Click</button>
        </>
      );
    };
    export default Simple_Example;

    Output

    " style="height: 631px;">

    In the above code, we have imported the hook from the library and used it like any other hook following all the rules as per the React documentation. We are just doing some basic animation using the CSS Property color, but we can use any other CSS Property like size, transform, translate, etc. to animate the app in the same way.

    The syntax of the useSpring hook is a bit different as it is seen in the above code. We have defined an object ‘props’ in our case (name doesn’t matter) and passed the values using the basic definition of the React Spring as defining an initial place and the final place or state and putting it in the style attribute of h1 tag.

    The values that this object returns are not static and can update themselves, and thus regular tags like h1 or div or any other HTML tag won't be enough to contain it. Thus all the HTML tags should be updated to <animated.tagName> or to keep it simple the wrapper tag. Without the wrapper tag, our animation will not work.

    The above approach is a very basic approach that one should at least know about. But there is a shorthand version of this as well. 

    If you are having trouble keeping up or have some doubts about where to start learning React JS, check out web development certification online and get started in your React Journey.

    ShortHand Style

    In this, we can avoid the boilerplate code of from and to and just pass the CSS style property with the ternary operator and the rest of the code remains the same.

      const props = useSpring({//applying hooks
       color: flip ? "blue": "red"
      });

    The benefit of this code is that now the animation rather than depending upon the form and a situation depends upon whether the flip state is true or false which initially is set to false and we can toggle between both the form and to situations with the setFlip function.

    Now that we have understood the basic syntax of React Spring and made an app with animation, we can move on to other properties which are again common for all other hooks as well and will help us understand this library even more.

    Interpolations 

    In the above example, we have just made a single color animation that triggers only when we click the button and returns when we click it again. But what if we could do more like adding a bunch of animations that will get triggered at the same time like changing color and moving in the 2D plane, etc.

    We just need to extract the values from the useSpring hook and use the interpolate property to destructure it and use it with ease in our apps.

    import { useState } from "react";
    import { useSpring, animated } from "react-spring";
    const Interpolate = () => {
      const [on, toggle] = useState(false);
      const { xy, c } = useSpring({ // extracted values from the object props
        from: { xy: [0, 0], c: "green" },
        xy: on ? [800, 200] : [0, 0],
        c: on ? "red" : "green",
      });
      return (
        <div>
          <animated.h1
            style={{
              transform:xy.interpolate((x,y) => `translate(${x}px, ${y}px)`),
              color: c.interpolate((c) => c),
            }}
          >
            {!on ? "I'm here" : "Now I'm over here"}
          </animated.h1>
          <button onClick={() => toggle(!on)}>Change</button>
        </div>
      );
    };
    export default Interpolate;

    Output

    " style="height: 567px;">

    In the above code, we have extracted values like x, y, and c from the object responsible for storing static values and giving non-static ones for animations. These values represent the x and y coordinates and the color which we have changed in the previous example and this was all possible because of the interpolation property of useSpring Hook.

    Notice that we have written the coordinates in the px format and color in the name format, we can change these conversions as well like we can change color using their RGB values for hex codes and as for coordinates, we can have them in % or in rem. There are endless possibilities we can use to style as well as animate our app.

    NameUnits
    Number
    Colorrgb / rgba / hsl / hsla / gradients
    Absolute Lengthcm / mm / in / px / pt /  pc
    Relative Lengthem / ex / ch / rem / vw / vh / vmin / vmax / %
    Anglesdeg / rad / grad / turn
    Flex and Gridfr
    SVG
    Arrays - 3D and 3D
    String PatternTransform / border / box-shadow
    Non-animatable String ValuesVisibility / pointer events
    Scrollto top / bottom / left / right

    The list is endless as we can all other CSS Properties as well with all its units like the ones shown above

    const props = useSpring({
      vector: [0, 10, 30],
      display: "block",
      padding: 20,
      background: "linear-gradient(to right, #009fff, #ec2f4b)",
      transform: "translate3d(0px,0,0) scale(1) rotateX(0deg)",
      boxShadow: "0px 10px 20px 0px rgba(0,0,0,0.4)",
      borderBottom: "10px solid #2D3747",
      shape: "M20,20 L20,380 L380,380 L380,20 L20,20 Z",
      textShadow: "0px 5px 15px rgba(255,255,255,0.5)",
      color: "var(--darkModeColor)",
    });

    In the above code, we have extracted some values for interpolation from the animation object to give our app a flexibility when it comes to animations, this trick is called Shorthand Style Props.

    It is similar to the Short Hand style we just saw earlier but in this we are extracting values from the object to get the same animation which similar to the ShortHand Style depends upon the state change.

    x, y, z;
    translate, translateX, translateY, translate3d;
    rotate, rotateX, rotateY, rotate3d;
    scale, scaleX, scaleY, scale3d;
    skew, skewX, skewY;
    matrix, matrix3d;

    Auto Animations

    The term auto animation sounds interesting for the first time but how is it taken care of with React Spring is on a whole nother level and we need another blog to explain that. Thankfully someone else has already done that for us.  

    We will only be explaining what's going on in brief with the code, rest is already given in chrisberry blog.

    import React, { useState, useEffect } from "react";
    import { useSpring, animated } from "react-spring";
    import { useMeasure } from "react-use";
    import style from "./accordion.module.css";
    import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
    import { faChevronDown } from "@fortawesome/free-solid-svg-icons";
    const Accordion = () => {
     const defaultHeight = "100px";
     // Manages the open or cloased state of the accordion
     const [open, toggle] = useState(false);
     // The height of the content inside of the accordion
     const [contentHeight, setContentHeight] = useState(defaultHeight);
     // Gets the height of the element (ref)
     const [ref, { height }] = useMeasure();
     // Animations
     const expand = useSpring({
       config: { friction: 10 },
       height: open ? `${contentHeight}px` : defaultHeight
     });
     const spin = useSpring({
       config: { friction: 10 },
       transform: open ? "rotate(180deg)" : "rotate(0deg)"
     });
     useEffect(() => {
       //Sets initial height
       setContentHeight(height);
       //Adds resize event listener
       window.addEventListener("resize", setContentHeight(height));
       // Clean-up
       return window.removeEventListener("resize", setContentHeight(height));
     }, [height]);
     return (
       <div className={style.wrapper}>
         <animated.div className={style.accordion} style={expand}>
           <div ref={ref} className={style.content}>
             <p>
               Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi at
               augue laoreet, eleifend turpis a, tincidunt velit. Curabitur vitae
               felis sit amet arcu blandit pellentesque quis vitae odio. Aenean
               pharetra eu felis non suscipit. Etiam fermentum enim sit amet magna
               scelerisque, eu mattis ligula tristique. Aliquam sed cursus odio,
               sit amet condimentum eros. Proin molestie commodo urna, eget
               accumsan tellus laoreet ut. Morbi id est eu lorem tempor cursus.
               Aenean vitae ultrices sem. Phasellus venenatis velit in ultrices
               interdum. Cras semper, justo a maximus iaculis, nisl metus luctus
               nisl, ac sodales odio mauris et ante. Donec ipsum est, auctor a
               lorem ac, rutrum elementum magna.
             </p>
           </div>
         </animated.div>
         <animated.button
           className={style.expand}
           onClick={() => toggle(!open)}
           style={spin}
         >
           <FontAwesomeIcon icon={faChevronDown} />
         </animated.button>
       </div>
     );
    };
    export default Accordion;

    What we are doing in this is building an accordion which upon toggling adjust itself automatically according to the height of the text as you can see in the output below.

    Output

    " style="height: 567px;">

    Using CSS Keyframes with Interpolations

    We have seen in all our codes that we can only go from 0 to 1 or from initial to final, but what if we have to change animations in the middle of this or on specific intervals like at a gap of 25%.

    Using CSS Keyframes with Interpolation is the solution to this problem. Like in Keyframes we used to animate with ranges like 25%, 50%, etc. The same principle will be applied here, the only difference will be that here it will not be in % rather in point value as it lies between 0 and 1.

    import React, { useState } from "react";
    import { useSpring, animated } from "react-spring";
    const Adinter = () => {
      const [on, toggle] = useState(false);
      const { x, c } = useSpring({
        from: { xy: [0, 0], c: 0 },
        x: on ? 1 : 0,
        c: on ? 1 : 0,
      });
      return (
        <div>
          <animated.h1
            style={{
              transform: x
                .interpolate({
                  range: [0, 0.25, 0.5, 0.75, 1],
                  output: [0, 80, 240, 480, 960],
                })
                .interpolate((x) => `translateX(${x}px)`),
              color: c
                .interpolate({
                  range: [0, 0.5, 1],
                  output: ["red", "blue", "green"],
                })
                .interpolate((c) => c),
            }}
          >
            {!on ? "I'm here" : "Now don't know where I'm going"}
          </animated.h1>
          <button onClick={() => toggle(!on)}>Change</button>
        </div>
      );
    };
    export default Adinter;

    Output

    " style="height: 567px;">

    There are many more properties and examples that you will find in the documentation of the React Spring which will give us a better understanding of what and how much we can accomplish with this library.

    Looking for the best Python course near me? Unleash your coding potential with our unique and catchy Python tutorials. Join now and become a Python pro!

    Conclusion

    In this blog, we have mainly discussed the what and how of React Spring and some pretty simple use cases which we think are very essential in understanding this concept as the same principles apply to other hooks as well, and knowing how to animate our React Component in every situation is the work of front-end developers like us.

    If you are new to the world of React and want to make awesome animations and apps like these, check out KnowledgeHut’s React js learning path and get started on the path of becoming a front-end developer.

    Frequently Asked Questions (FAQs)

    1How to Install React Spring with NPM?

    React Spring can be installed with NPM using the following comment - npm i react-spring. 

    2Can You Use React Spring with Gatsby?

    Yes, we can use React Spring with Gatsby. There is a plugin called the gatsby page transition link but it only supports duration-based animations. More info here: Spectrum.

    3How Do You Use React Animation?

    As told in the blog itself that there are multiple ways we can animate our React App. One of them is using plain old CSS transitions or keyframes while the other includes npm packages or libraries like React Spring we have discussed in this blog.

    4What is useSpring?

    As explained in the blog, the useSpring hook is the basic hook which we can use for animating our React App in many different ways as we have seen in the blog.

    Profile

    Ateev Duggal

    Blog Author

    "I am Ateev Duggal, a front-end web developer, and a blogger. I write blogs mainly on React JS and have an experience of over 1.5 years of freelancing. I have worked on both static and dynamic projects again using React JS like a table to show clients data which was fetched using API, a review slider, pagination component, etc, and many websites like Parent, landing pages for Ataota, and many more.
    Some of my blogs have been published on freecodecamp, dev.to, Medium, Hashnode, and many other blogging platforms and developer's communities.
    My Primary skills not only include React JS but HTML5, CSS3, JS, Jquery, Git, and Bootstrap also. You can visit my GitHub Profile and LinkedIn profile for more information about me or you can visit my Website at tekolio.com".

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon