Animate Elements With the useSpring Hook

Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 3 years ago

In this lesson React Spring's useSpring hook is used to animate CSS properties.

You will also learn how to use animated to extend native elements to receive animated values.

Christian Nwamba: [0:00] Here I have this animation that goes from to 100. Basically, it draws the width of a box from to 100 at the rate of one second. If I reload the browser, you should see the line go from A to B.

[0:16] Instead of just going from A to B, let's take a look at another example which is what makes react-spring release stand out from other React animation libraries.

[0:27] Let's say we take our width property and just replace it with to. This is going to take an async function. This async function will receive a next argument. What this function would do is to look infinitely and for each state of the loop, call the next method using the await keyword.

[0:54] What we'll give the next method is where we want to animate to. Let's say we want to animate to , and then we also want to animate to 100. At every stage of this animation, we would go from to 100, and from 100 to . If we look at the browser, we should get a nice loop in our animation.

[1:19] This is where react-spring starts getting interesting. Let's say I add an onClick event to this button. Every single time a user clicks this button, I want to stop this animation.

[1:34] If you're wondering where the stop method comes from, it can be received from the useSpring method. useSpring returns props, set, and stop. Since we are not using the set method, we can just replace it with an underscore.

[1:49] Generally, in other animation libraries, what would happen when you click the stop method is that the animation would abruptly stop at the current phase. This doesn't depict what things look like in real life. If you are driving a car, when you accelerate, it takes time for it to get to its full speed. When you hit the brake, it takes some time before the car comes to a full stop.

[2:11] That's why the same thing happens here. While we're moving from A to B, if I click, you can see it tries to go back to where it was originally. It doesn't just stop abruptly at the middle of the animation. It tries to reset the animation back to where it was before it took off.

Thomas Burleson
Thomas Burleson
~ 4 years ago

This demo does not run!

Christian Nwamba
Christian Nwambainstructor
~ 4 years ago

Fixed now, Thomas. Thanks for catching that!

Thomas Burleson
Thomas Burleson
~ 4 years ago

I tried isPaused with useState + while (!isPaused). But the stop() did not stop the spring animations. How do I stop the animation and restart ?

Markdown supported.
Become a member to join the discussionEnroll Today