Animated.event for scroll-driven parallax
Mapping native events to animated values.
Animated.event maps an event path to an Animated.Value, wire it to onScroll with useNativeDriver, then interpolate the value for header transform.
WHAT THIS TESTS Whether you can hook an animated value straight to a native event stream and shape it with interpolation, instead of recomputing styles in JavaScript on every scroll frame.
A GOOD ANSWER COVERS Animated.event accepts an array mirroring the arguments of the native event and a config object. For scroll you pass a mapping that points contentOffset.y at your scrollY Animated.Value, plus useNativeDriver true. You attach the result to the onScroll prop of an Animated.ScrollView, typically with scrollEventThrottle set to 16. Because the mapping is declared natively, the value updates without a JS round trip. You then call scrollY.interpolate with an inputRange and outputRange to derive header styles, for example translating the header up more slowly than the content scrolls to create parallax, or fading and shrinking it. Using extrapolate clamp prevents the header from over-translating past its range.
COMMON WRONG ANSWERS Writing an onScroll arrow function that pulls event.nativeEvent.contentOffset.y and calls setState, which janks under load. Forgetting useNativeDriver, so each frame still hits the bridge. Using a plain ScrollView instead of Animated.ScrollView. Interpolating without clamping, letting the header keep moving past its intended bounds.
LIKELY FOLLOW-UPS What does scrollEventThrottle control, why can the native driver only animate transform and opacity here, how would you do this in Reanimated with useAnimatedScrollHandler, and how do you combine multiple interpolations.
ONE CONCRETE EXAMPLE const scrollY = useRef new Animated.Value 0. onScroll equals Animated.event mapping nativeEvent.contentOffset.y to scrollY with useNativeDriver true. The header's transform translateY is scrollY.interpolate from inputRange 0 to 200 to outputRange 0 to negative 60 with clamp, and its opacity interpolates 0 to 200 down to 0. As the user scrolls, the header drifts and fades at a fraction of the content speed, all driven natively.
Read the original → reactnative.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.