CodeBlanks Logo Icon CodeBlanks

useAnimatedStyle

Learn animated styles with useAnimatedStyle.

useAnimatedStyle

useAnimatedStyle produces an animated style object based on a shared value. The returned style is passed to the style prop of Animated.View. Example: const animatedStyle = useAnimatedStyle(() => ({ transform: [{ translateX: offset.value }] })).

Inside the function .value is read and a style object is returned. This style is automatically recalculated on the UI thread as the value changes. No render is triggered on the JavaScript side; this is why animations are very smooth.

Using with Animated.View

To apply the animated style you pass it to the style prop of Animated.View. Example: <Animated.View style={[styles.box, animatedStyle]} />. Here styles.box carries static, animatedStyle carries dynamic styles. They are merged.

Passing the styles inside an array is important; this way both static and animated rules work together. Animated.View is the animated version of a normal View; it updates on the UI thread.

Practice Write the animated style

Import useAnimatedStyle from react-native-reanimated. Produce an animated style with const animatedStyle = useAnimatedStyle(() => ({ transform: [{ translateX: offset.value }] })). Define offset with useSharedValue(0).

Starter code

App.js
import React from 'react';
import { useSharedValue } from 'react-native-reanimated';

export function useMove() {
  const offset = useSharedValue(0);
  // define animatedStyle with useAnimatedStyle

  return { offset, animatedStyle };
}

Sample solution

App.js
import React from 'react';
import { useAnimatedStyle, useSharedValue } from 'react-native-reanimated';

export function useMove() {
  const offset = useSharedValue(0);
  const animatedStyle = useAnimatedStyle(() => ({
    transform: [{ translateX: offset.value }],
  }));

  return { offset, animatedStyle };
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 The useAnimatedStyle call

Question
const animatedStyle = ____(() => ({ transform: [{ translateX: offset.value }] }));
Answer
const animatedStyle = useAnimatedStyle(() => ({ transform: [{ translateX: offset.value }] }));

Explanation: useAnimatedStyle produces an animated style.

2 Match the style parts

Term Meaning
useAnimatedStyle Produces the style
Animated.View Applies the style
translateX Horizontal shift
offset.value Style source

3 Why is Animated.View preferred?

  • Because it updates on the UI thread
  • Because it is not a hook
  • Because it deletes styles
  • Because it uses less memory Correct answer

Explanation: Animated.View updates on the UI thread; it is smooth.

All lessons in Advanced