DEV Community

Billy Jacoby
Billy Jacoby

Posted on • Updated on • Originally published at billyjacoby.com

Greensock Animations using React Hooks

This is a brief tutorial on how to animate components on demand with Greensock and React hooks.

We'll be using create react app in this tutorial.

If you want to see a quick demo you can check it out here first:

https://billyjacoby.github.io/gsap-with-hooks/

To begin create a new app:

create-react-app gsap-with-hooks
cd gsap-with-hooks

The only other dependency we will need for this tutorial is GSAP.

yarn add gsap

Start the development server so that we can see our changes

yarn start

Since we will be adding our own animations here, remove the lines that animate the React Logo from src/App.css

Looking at the development server, the logo should no longer be spinning.

Now we're going to add three buttons to our app that Pause, Play, and Reverse our animation. We're also going to turn the App component into a functional component.

Your App.js should look similar to this after adding the buttons:

Okay, now for the real work. In order to accomplish this correctly only using a functional component we will need to import useState, useRef, and useEffect from react.

Replace the import React from "react"; line with:

import React, {useState, useRef, useEffect} from "react";

The first thing we'll do is create a new ref and store the react img logo in it. This will ensure that this node is loaded on the DOM before we try to animate it with Greensock.

The next thing we'll do is create a react state object to store our animation function in. This will ensure that we are always accessing the already existing animation function as opposed to creating a new one.

Next we have to use the useEffect hook to make sure that the animation is only created once the DOM has been rendered. We will create our animation function here and store it in our state object.

Since we don't want our animation to play as soon as it's loaded, we throw the .pause() method on the end of it. This will enable us to control when it starts rather than just starting on loading.

The last thing to do is to wire up our buttons to do their jobs!

Note that the reverse method basically rewinds the animation, so it will only work if the animation has been running for a few seconds.

Now this is obviously just the beginning of what you can do with react hooks and GSAP.

I'll be posting a tutorial shortly on how to use the IntersectionObserver API with GSAP to animate objects when they appear on the screen soon.

Thanks for reading, and if you're interested in any other short tutorials be sure to let me know in the comments below!

Top comments (3)

Collapse
 
ooloth profile image
Michael Uloth

Nice tutorial!

Collapse
 
billyjacoby profile image
Billy Jacoby

Thanks man!

Collapse
 
daniilgri profile image
Danil Grishaev

Thanks, just in time found your tutorial.