21-Dec

React

useNativeDriving with React Native

Animations are awesome. Make sure they are as smooth as they can.

3 min read

·

By Hannes Waller

·

December 21, 2018

I love React Native. It might have its flaws, but it's the most fun I've had developing. This short write up is an introduction on how to make the most out of your animations with useNativeDriver. If you're already a somewhat seasoned React Native developer this probably won't be news to you.

Animation in React Native is usually fairly straightforward. This article is about the Animated API, which ships with React Native. There are some cool alternatives, like Reanimated from Expo, which extends Animated. And then there's Lottie, Pose and a bunch of other exciting things. But lets get back on topic.

How to use it?

As you might know, most of the stuff going on in React Native occurs on the JS thread. While this works well most of the time, it might get clogged by things going on in your app, resulting in it being unresponsive and/or slow. That's where useNativeDriver might come to the rescue. In short it tells the app to run said animation on the UI thread instead of the JS thread. In other words, it runs in the world of native, which offers higher performance and you don't have to worry about the JS thread being blocked by something else.

There are some limitations though. For instance, you can only use it while animating on non-layout properties. So transforms and opacity are fine, while position and flexbox properties aren't.

The only thing you need to do to actually put your animations on the UI thread is to pass useNativeDriver: true to your animation properties. Like so:

Animated.timing(this.awesomeAnimation, {
    toValue: 1,
    duration: 250,
    useNativeDriver: true,
}).start()

And that's it.

Unsure whether or not you have a problem?

Running animations on the JS thread can be perfectly fine. I tend to use useNativeDriver whenever I can, but you certainly don't have to. An easy way to determine if you might have a problem is to bring up the developer menu in your simulator. Just press CMD + D for iOS or CMD + M for Android. If running on an actual device just shake it like a somewhat fragile maracas.

If you got the developer menu showing, tap or click the Show perf monitor option you'll see this:

Showing the perf monitor

If you use your app now you might see the frames per second jumping up and down. If the JS thread keeps dropping frames you are most likely doing too heavy lifting here, something that useNativeDriver might help you to solve.

Up next...

Loading…