Photo by Mark Tuzman on Unsplash

How to create velocity based animations in React

CSS is an easy and declarative tool to implement styling and quick. For the most part, you can make an app look great without touching a single line of code. Awesome! But it does raise a few limitations with animations, however. Without having the ability to obtain a reference to the target element itself, and/or the data that is bound to it, animations cannot be pixel perfect. Indeed, some developers are aware of that, and consequently, have come up with various libraries and frameworks, of which D3 is included.

D3 allows you to bind arbitrary data to a Document Object Model (DOM), and then apply data-driven transformations to the document — D3

So yeah, D3 is great, but if you know a thing or two about it, you’ve probably realized that it’s a hell of a complicated library. And so do other libraries/frameworks that come with a lot of overhead, I believe. So let’s take all these 3rd party assets out of the picture for a moment and try to really understand the underlying mechanism for creating pixel perfect animations.

A sketch of the values returned by getBoundlingClientRect(). Source: MDN
The final state of the animation
Duration based animation
  • At the layout phase, right before drawing anything to the screen, wet the dimensions of the element with getBoudningClientRect().
  • We apply an animation at a rate of 2px/ms by setting a duration that is derived from the element’s height.
Velocity based animations

Updates scheduled inside useLayoutEffect will be flushed synchronously, before the browser has a chance to paint — React

If you’ll think creatively you’ll discover that the design pattern in this article can be applied in many use cases and can be stretched even further. While you’re at it, I recommend you to look at:

Eytan is a JavaScript artist who comes from the land of the Promise(). His hobbies are eating, sleeping; and open-source… He loves open-source.