React Native Reanimated

Declarative Animation in React-Native

Updated: 03 September 2023

References:

Initialize an App

To create a new app, do the following using the Expo CLI (I’ve covered the basics for this here)

Terminal window
1
expo init native-animation

And then select the option for Blank (Typescript)

Install Reanimated

Terminal window
1
yarn add react-native-reanimated

Optionally, to add support for Web update your babel.config.js file add the reanimated plugin: react-native-reanimated/plugin, so your file should now look like this:

1
module.exports = function (api) {
2
api.cache(true)
3
return {
4
presets: ['babel-preset-expo'],
5
plugins: ['react-native-reanimated/plugin'],
6
}
7
}

Updating Views

Usually when creating components you can mix static and dynamic styles, this allows us to mix styles from our StyleSheet with styles from a useAnimatedStyle hook, so something like this:

1
const animatedStyles = useAnimatedStyle(() => {
2
return {
3
transform: [{ translateX: 100 }],
4
}
5
})
6
7
return <Animated.View style={[styles.box, animatedStyles]} />

Managing Animated State

Shared Values are values that can be read from both the JS and UI Threads and help to:

  • Carry data
  • Drive Animations
  • Provide Relativeness

Can be created using the useSharedValue hook, similar to Animated.value but can carry any type of data that we want

These values can also be directly assigned to in order to update them

1
const progress = useSharedValue(0)
2
3
const animatedStyles = useAnimatedStyle(() => {
4
return {
5
transform: [{ translateX: progress.value * 100 }],
6
}
7
})
8
9
// can be modified directly - they are reactive
10
const onPress = () => (progress.value += 1)
11
12
return <Animated.View style={[styles.box, animatedStyles]} />

Another hook we can use to calculate a value based on the value of sharedValue is the useDerivedValue hook, which can be used in association with the above example like so:

1
const progress = useSharedValue(0)
2
const translateX = useDerivedValue(() => progress.value * 100)
3
4
const animatedStyles = useAnimatedStyle(() => {
5
return {
6
transform: [{ translateX }],
7
}
8
})
9
10
const onPress = () => (progress.value += 1)
11
12
return <Animated.View style={[styles.box, animatedStyles]} />

Animation

Whe working with animations there’s a concept of an animation assigner, this is basically a function that creates an animated value that can then be assigned to a shared value. Some functions available for this are:

  • Easing functions like Easing.bezier or Easing.bounce
  • withTiming to set an animation to happen over a set amount of time
  • withSpring to make an animation springy

These can be used like so:

1
const style = useAnimatedStyle(() => {
2
const duration = 500
3
const w = withSpring(width.value, { duration, easing: Easing.bounce })
4
return {
5
width: w,
6
}
7
}, [])

Additionally there are modifiers that can be used with an animation, something like delay:

1
const w = delay(100, withSpring(width.value))

Gestures

Gesture handling in React Native is usually done using the react-native-gesture-handler library. At the top-level the library exposes gestureHandlerRootHOC and GestureHandlerRootView. Before your application will be able to register gestures you have to wrap your application with either the HOC or RootView mentioned above

This would be done at the top-level of your app like so

Using the gestureHandlerRootHOC:

App.tsx

1
import { gestureHandlerRootHOC } from 'react-native-gesture-handler'
2
// ...
3
4
function App() {
5
// app component stuff
6
}
7
8
export default gestureHandlerRootHOC(App)

Or using GestureHandlerRootView:

App.tsx

1
import { GestureHandlerRootView } from 'react-native-gesture-handler'
2
// ...
3
4
export default function App() {
5
// app component stuff
6
7
return <GestureHandlerRootView>{/* rest of app */}</GestureHandlerRootView>
8
}

When handling gestures we have a useAnimatedGestureHandler which can take an object of method handlers, for example setting an onActive handler like below

1
import { PanGestureHandler } from 'react-native-gesture-handler'
2
3
// ...
4
5
const translateX = useSharedValue(0.0)
6
const translateY = useSharedValue(0.0)
7
8
const gestureHandler = useAnimatedGestureHandler({
9
onActive: (e) => {
10
translateX.value = e.translationX
11
translateY.value = e.translationY
12
},
13
})
14
15
const style = useAnimatedStyle(() => {
16
return {
17
transform: [
18
{ translateX: translateX.value },
19
{ translateY: translateY.value },
20
],
21
}
22
}, [])
23
24
return (
25
<PanGestureHandler onGestureEvent={gestureHandler}>
26
<Animated.View style={[styles.box, style]} />
27
</PanGestureHandler>
28
)

We can also add an animation to the value we calculate, so something like withSpring

1
const gestureHandler = useAnimatedGestureHandler({
2
onActive: (e) => {
3
translateX.value = withSpring(e.translationX)
4
translateY.value = withSpring(e.translationY)
5
},
6
})

Worklets

In React-Native we have a few main threads in which code is executed:

  • The Main JS thread where our JavaScript code is executed
  • The UI Thread in which rendering Native views are done
  • The Native Modules thread where Native Code is run

Reanimated adds to this by running some additional JS code in the UI Thread instead of the main JS thread, these are called worklets, and they’re pretty much just functions

A Worklet can be defined using either the worklet directive or is implied for a lambda used in the useAnimatedStyle hook

A simple worklet can look like so:

1
const myWorklet = (a: number, b: number) => {
2
'worklet'
3
return a + b
4
}
5
6
const onPress = () => {
7
runOnUI(myWorklet)(1, 2)
8
}

Or, in the useAnimatedStyle hook:

1
const width = useSharedValue(200)
2
3
const style = useAnimatedStyle(() => {
4
// this function is also a worklet
5
return {
6
width: withSpring(width.value),
7
}
8
}, [])
9
10
const onPress = () => {
11
// unusual in react, but we can modify this value directly here
12
width.value = Math.random() * 500
13
}
  • useSharedValue creates a value that can be accessed from the UI Thread
  • useAnimatedStyle uses a worklet which can returns a style
  • withSpring creates an interpolated value

Using the above, we can render an element with a variable width using the Animated.View

1
export default function App() {
2
const width = useSharedValue(200)
3
4
const style = useAnimatedStyle(() => {
5
const duration = 500
6
const w = withSpring(width.value)
7
return {
8
width: w,
9
}
10
}, [])
11
12
const onPress = () => {
13
// unusual in react, but we can modify this value directly here
14
width.value = Math.random() * 500
15
}
16
17
return (
18
<View style={styles.container}>
19
<StatusBar style="auto" />
20
<Animated.View style={[styles.box, style]} />
21
<Button color="black" onPress={onPress} title="Change Size" />
22
</View>
23
)
24
}
25
26
const styles = StyleSheet.create({
27
container: {
28
flex: 1,
29
backgroundColor: '#fff',
30
alignItems: 'center',
31
justifyContent: 'center',
32
},
33
box: {
34
height: 200,
35
backgroundColor: 'blue',
36
marginBottom: 20,
37
},
38
})

Note that though worklets can call non-worklet methods, those methods will be executed on the JS Thread and not the UI Thread