Animating with React Hooks and RxJS

Oct 29, 2018

The introduction of React Hooks got me excited to try them out on an animation prototype. A dribble shot by @tmgrhm looked like a good opportunity to me.

Try it live.

Such apps tend to have quite a bit of side effects if you don't use an abstraction which takes care of that. Also from my experience, building fancy animations usually makes code harder to read. That's why I thought it might be interesting to see if React Hooks are a good fit for this.

I initially tried running the animation loop via setState, but that turned out to be too slow. Therefore I wanted something that bypasses React altogether for my animation purposes: Introducing RxJS. Observables are interesting for gestures where a single touch movement controls multiple effects.

In my case I'm reading scrollTop on every animation frame, feed that into a stream which all animatable elements subscribe to and transform it as necessary. Reading scrollTop via requestAnimationFrame produces better results in comparison to a scroll listener, as the latter can fire too often which will cause jank. Therefore every frame starts with a single read operation from the DOM followed by a few write operations. That avoids layout thrashing and reduces CPU work.

A bit of JavaScript is necessary, but the animation runs with 60 FPS on mobile (screenshot from a MacBook Pro with 4x CPU slowdown).

Credit for using RxJS for animation goes to @DavidKPiano, @BenLesh and @appsforartists.

To me, the most promising aspect of Hooks was having another tool in the box to create abstractions for shared behaviour. This can lead to slimmer components. Also useEffect is just amazing in comparison to componentDidMount, -DidUpdate and -WillUnmount.

The code is available on Github.

Read next

Songwriting assistant prototype

I needed an excuse to try out the Animated API of React Native.

Aug 22, 2016