this repo has no description

Update output with titles

+5 -9
out/llms-full-nativewind.txt
···
***
-
## Accessing and Managing Device Color Scheme
+
## useColorScheme()
The `useColorScheme()` function provides a way to access and manage the device's current color scheme.
···
These classes are used to define how the background of an element is clipped, with support limited to web browsers.
-
## Responsive Design in Nativewind
+
## Responsive Design
**Note:**\
The default theme of Nativewind is not specifically tailored for native devices. It currently employs breakpoints that are primarily intended for web applications.
Nativewind's approach to responsive design mirrors that of Tailwind CSS. For detailed information, please consult the official Tailwind CSS documentation.
-
## remapProps Utility in Nativewind
+
## remapProps
Nativewind offers a utility called `remapProps` to streamline the integration of third-party components that have multiple "style" props. This tool allows developers to map Tailwind CSS class names to these style props, enhancing ease of use and consistency.
···
This configuration allows you to specify additional class attributes that Tailwind CSS will recognize and apply.
-
```markdown
-
## Content Rules in Nativewind
+
## Content
Nativewind adheres to the same content configuration guidelines as Tailwind CSS. For detailed information and solutions to potential issues, consult the official Tailwind CSS documentation.
-
```
-
-
This reformatted markdown maintains the original message while ensuring clarity and conciseness for an AI context.
## Overflow
···
```
-
## Usage
+
## Top / Right / Bottom / Left
For detailed information, please consult the Tailwind CSS documentation.
+46 -50
out/llms-full-react-native-gesture-handler.txt
···
Software Mansion is a team of React Native Core Contributors and experts specializing in resolving various React Native challenges. Whether you need assistance with gestures, animations, or general development, we are here to help.
-
## Installation Guide for react-native-gesture-handler
+
## Installation
### Requirements
···
Ensure each screen in your app is wrapped with `GestureHandlerRootView` as native navigation libraries map each screen to a separate root view.
-
## Rotation Gesture
+
## Rotation gesture
A continuous gesture capable of recognizing and tracking rotation movements. Activation occurs when fingers are placed on the screen and move in a specific manner.
···
- **`pointerType`**: Type of pointer device, represented by the `PointerType` enum (`TOUCH`, `STYLUS`, `MOUSE`, `KEY`, `OTHER`).
-
## Pinch Gesture
+
## Pinch gesture
A continuous gesture that recognizes pinch gestures, allowing for tracking the distance between two fingers to scale or zoom content. The gesture activates when fingers are placed on the screen and change their position. A callback can be used for continuous tracking of the pinch gesture, providing information about velocity, anchor (focal) point, and scale.
···
}
```
-
## Pan Gesture
+
## Pan gesture
A pan gesture recognizes and tracks a continuous dragging motion. It activates when a finger touches the screen and moves beyond an initial distance.
···
}
```
-
## Gesture States and Events
+
## Gesture states & events
Each gesture can be conceptualized as a "state machine." At any given moment, each handler instance is assigned a state that may change due to new touch events or specific conditions imposed by the touch system.
···
- **`onPointerCancelled`**
- Called when no further pointer information is available due to gesture completion or interruption. May involve multiple pointers due to event batching.
-
## Handler State Overview
+
## Handler State
Gesture handlers are conceptualized as "state machines," where each instance maintains an assigned state that can change due to new touch events or be altered by the touch system under specific conditions. There are six possible states for a gesture handler:
···
Signifies the end of a gesture with touches indicating completion. The state transitions to `UNDETERMINED` after resetting.
-
```markdown
-
# Legacy Gesture Handlers
+
## Legacy Gesture Handlers
-
## Overview
+
### Overview
The legacy gesture handler API is scheduled for removal in upcoming versions of Gesture Handler. Users are encouraged to transition to the new gestures API. For detailed migration instructions, refer to the provided upgrading guide.
-
## Cross-Handler Interactions
+
### Cross-Handler Interactions
The previous cross-handler interaction capabilities will be deprecated in future releases. Transitioning to the updated gestures API is recommended. Consult the upgrading guide for further details.
-
## Common Handler Properties
+
### Common Handler Properties
Properties common across handlers in the old API are slated for removal. Users should adopt the new gestures API and refer to the upgrading guide for assistance.
-
## Specific Gesture Handlers
+
### Specific Gesture Handlers
-
### Pan
+
#### Pan
The pan gesture handler from the legacy API will be deprecated. Transitioning to the gestures API is advised. See the upgrading guide for more information.
-
### Tap
+
#### Tap
The tap gesture handler in the old API will no longer be supported. Users should migrate to the new gestures API. Refer to the upgrading guide for guidance.
-
### Long Press
+
#### Long Press
Long press functionality from the legacy API will be removed. Transitioning to the gestures API is recommended. Consult the upgrading guide for more details.
-
### Rotation
+
#### Rotation
The rotation gesture handler in the old API will be deprecated. Migrating to the gestures API is advised. See the upgrading guide for further information.
-
### Fling
+
#### Fling
Fling gesture handling from the legacy API will be removed. Users should transition to the new gestures API. Refer to the upgrading guide for assistance.
-
### Pinch
+
#### Pinch
The pinch gesture handler in the old API will no longer be supported. Transitioning to the gestures API is recommended. Consult the upgrading guide for more details.
-
### Force Touch
+
#### Force Touch
Force touch functionality from the legacy API will be deprecated. Migrating to the gestures API is advised. See the upgrading guide for further information.
-
## NativeView
+
### NativeView
The `NativeView` component in the old API will be removed. Users should adopt the new gestures API and refer to the upgrading guide for assistance.
-
## createNativeWrapper()
+
### createNativeWrapper()
The `createNativeWrapper()` function from the legacy API will no longer be supported. Transitioning to the gestures API is recommended. Consult the upgrading guide for more details.
-
```
## Testing with Jest
···
By setting `touchAction` to `"pan-y"`, you allow vertical panning, which helps maintain scroll functionality in your custom swipeable component.
-
## Cross Handler Interactions
+
## Cross handler interactions
**Warning:** The old API will be removed in future versions of Gesture Handler. Please migrate to the gestures API instead. Refer to our upgrading guide for more information.
···
);
```
-
## Fling Gesture
+
## Fling gesture
A discrete gesture activated by sufficiently long and fast movement. The gesture becomes ACTIVE when the movement meets these criteria, transitioning to END upon finger release. If the finger lifts before activation, recognition fails.
···
|`numberOfPointers`|Number of pointers currently on the screen.|
|`pointerType`|Type of pointer device, using `PointerType`: `TOUCH`, `STYLUS`, `MOUSE`, `KEY`, `OTHER`.|
-
## Common Handler Properties
+
## Common handler properties
**Warning:** The old API will be removed in future versions of Gesture Handler. Please migrate to the gestures API instead. Refer to our upgrading guide for more information.
···
- **Description:** Represents the number of pointers (fingers) currently on the screen.
-
## Hover Gesture
+
## Hover gesture
A continuous gesture designed to recognize hovering actions over a view. This can be triggered by moving a mouse or stylus above the view.
···
This example sets up a button that triggers an alert when held down for more than 800 milliseconds.
-
## Custom Swipeable Components in ScrollView (Web)
+
## Custom swipeable components inside ScrollView (web)
When developing custom swipeable components within a `ScrollView` on the web, you might opt for more control over their behavior by creating your own version instead of using pre-built solutions like ReanimatedSwipeable. However, one common issue encountered is that scrolling functionality may not work as expected after implementing a custom swipeable component.
···
By setting `touchAction` to `"pan-y"`, you allow the browser to handle vertical panning, which can resolve issues with scrolling when using custom swipeable components inside a `ScrollView`.
-
## Migrating Away from RNGHEnabledRootView
+
## Migrating off RNGHEnabledRootView
### Update `MainActivity.java`
···
**Note:** `GestureHandlerRootView` behaves like a standard `View`. To ensure it fills the screen, you must pass `{ flex: 1 }`, similar to how you would with a regular View. By default, it will take on the size of its nested content.
-
## Rotation Gesture Handler
+
## RotationGestureHandler
> **Warning:**\
> The old API will be deprecated in future versions of Gesture Handler. It is recommended to migrate to the gestures API. Refer to our upgrading guide for more details.
···
This example shows a button that triggers an alert when flinged to the right or left.
-
## Quick Start Guide
+
## Quick start
RNGH2 simplifies adding gestures to your application. To implement a gesture, wrap the target view with `GestureDetector`, define the desired gesture, and pass it to the detector.
···
Now, add the `Ball` component to a view in your app to see it in action!
-
## Native Gesture
+
## Native gesture
A gesture that integrates with other touch handling components within RNGH's gesture system. This integration facilitates interactions between gestures and native components, allowing them to establish relationships with other gestures.
···
**Note**: For a detailed example, refer to the Gesture Handler Example App.
-
## Manual Gesture
+
## Manual gesture
A manual gesture lacks specific activation criteria and event data. Its state must be managed manually using a state manager, ensuring it doesn't fail when all pointers are lifted from the screen.
···
- `KEY`: Keyboard
- `OTHER`: Unknown device type
-
## Migrating from `RNGestureHandlerEnabledRootView` (Android Only)
+
## Make sure to migrate off the \`RNGestureHandlerEnabledRootView\` (Android only)
The `RNGestureHandlerEnabledRootView`, required in Gesture Handler 1 for overriding `createRootView`, was deprecated in version 2.0 and removed by version 2.4 due to its association with difficult-to-debug crashes. If you're still using it, refer to the guide on migrating off RNGHEnabledRootView.
···
For relations between gestures on the same view, use the Gesture Composition API. For different views or old gesture handlers, replace `simultaneousHandlers` with `simultaneousWithExternalGesture`, and `waitFor` with `requireExternalGestureToFail`. Use `.withRef(refObject)` to pass a ref object to an old handler.
-
## Composed Gestures
+
## Composed gestures
Composed gestures such as `Race`, `Simultaneous`, and `Exclusive` offer a straightforward method for establishing relationships between different gestures. For further information, refer to the section on Gesture Composition.
···
This example demonstrates how to use the `Race` method to compose two gestures: a pan gesture and a long press gesture. The composed gesture is then used within a `GestureDetector` component, which wraps an `Animated.View`.
-
## Common Handler Properties
+
## Common handler properties
**Warning:** The old API will be removed in future versions of Gesture Handler. Please migrate to the gestures API instead. Refer to our upgrading guide for more information.
···
The `GestureStateManager` allows manual control over gesture states. Note that react-native-reanimated is required for its use, as it enables synchronous execution of methods within worklets.
-
## Touch Events
+
## Touch events
### Touch Event Attributes
···
- **absoluteY**: The Y coordinate of the current position of the touch relative to the window, expressed in point units. Recommended for use when the original view can be transformed due to a gesture.
-
## Gesture State Manager
+
## Gesture state manager
The `GestureStateManager` provides manual control over gesture states, requiring `react-native-reanimated` for synchronous execution of methods within worklets.
···
- **Purpose**: Transition the gesture to the `FAILED` state.
- **Effectiveness**: Ineffective if the handler has already finished.
-
## Touch Events
+
## Touch events
### Touch Event Attributes
···
- **absoluteY**: The Y coordinate of the current position of the touch relative to the window, expressed in point units. Recommended for use when the original view can be transformed due to a gesture.
-
## Gesture State Manager
+
## Gesture state manager
The `GestureStateManager` provides manual control over gesture states, requiring `react-native-reanimated` for synchronous execution of methods within worklets.
···
```
-
## Gesture Composition & Interactions
+
## Gesture composition & interactions
In RNGH2, composing gestures has been simplified compared to previous versions. There is no longer a need to create a reference for each gesture that depends on another one. Instead, you can utilize the Race, Simultaneous, and Exclusive methods provided by the Gesture object.
···
These methods facilitate more intuitive and flexible gesture interactions within your application.
-
## Manual Gestures
+
## Manual gestures
RNGH2 introduces manual gestures and touch events, allowing for custom gesture tracking. This guide demonstrates creating a simple gesture that tracks all pointers on the screen.
···
Manual gestures offer powerful customization, enabling complex interactions. Additionally, existing gestures can be modified with `manualActivation` to control activation behavior, such as implementing drag after a long press by setting `manualActivation` on a `PanGesture`.
-
## Pressable Component
+
## Pressable
### Overview
···
});
```
-
## Gesture Composition & Interactions
+
## Gesture composition & interactions
Composing gestures in RNGH2 is straightforward. You don't need to create a ref for each gesture that depends on another one. Instead, use `Race`, `Simultaneous`, and `Exclusive` methods provided by the `Gesture` object.
···
We are grateful for our sponsors who enable the development of this library and contribute to enhancing the React Native ecosystem. Special thanks to all our supporters!
-
## Troubleshooting Guide
+
## Troubleshooting
### Seeking Help with Issues
···
This ensures proper workletization for asynchronous operations within gestures.
-
## Tap Gesture
+
## Tap gesture
A tap gesture recognizes one or multiple taps. It detects brief touches on the screen by fingers, which must remain relatively stationary from their initial positions. You can configure tap gestures to recognize single, double, or triple taps based on specific requirements such as `minPointers`, `numberOfTaps`, `maxDist`, `maxDuration`, and `maxDelayMs`.
···
});
```
-
## Swipeable Component
+
## Swipeable
**Caution:** This component facilitates the implementation of swipeable rows or similar interactions. It renders its children within a panable container, allowing for horizontal swiping left and right. Depending on whether the user swipes left or right, one of two "action" containers can be displayed, rendered by `renderLeftActions` or `renderRightActions` props.
···
For a comparison of both touchable implementations, refer to our touchables example.
-
```markdown
-
# Handler State
+
## Handler State
Gesture handlers are conceptualized as "state machines" according to the description provided in "About Gesture Handlers". This means they operate through a series of states, transitioning between them based on specific inputs or events.
-
```
-
## How It Works
+
## How does it work?
### Units
+3655 -3817
out/llms-full-react-native-reanimated.txt
···
-
# React Native Reanimated
+
# React NativeReanimated
### Create Smooth Animations with an Excellent Developer Experience
···
|-|-|-|
|✅|✅|✅|
-
## useAnimatedScrollHandler
+
## Shared Element Transitions
-
The `useAnimatedScrollHandler` hook provides an event handler reference that can be utilized with React Native's scrollable components. This hook is part of the `react-native-reanimated` library.
+
> **Caution:**\
+
> Shared Element Transition is an experimental feature and not recommended for production use yet. Feedback is welcomed to enhance its implementation.
+
+
Shared Element Transition enables a smooth transformation of a component from one screen to another.
### Reference
```typescript
-
import { useAnimatedScrollHandler } from 'react-native-reanimated';
+
import Animated from 'react-native-reanimated';
-
function App() {
-
const offsetY = useSharedValue(0);
+
const Stack = createNativeStackNavigator();
-
const scrollHandler = useAnimatedScrollHandler((event) => {
-
offsetY.value = event.contentOffset.y;
-
});
-
-
// ...
-
-
return <Animated.ScrollView onScroll={scrollHandler} />;
+
function One({ navigation }) {
+
return (
+
<>
+
<Animated.View sharedTransitionTag="sharedTag" />
+
<Button title="Two" onPress={() => navigation.navigate('Two')} />
+
</>
+
);
}
-
```
-
-
#### Arguments
-
##### `handlers`
-
-
An object containing custom keys that correspond to native event names. Available keys include:
-
-
- `onScroll`
-
- `onBeginDrag`
-
- `onEndDrag`
-
- `onMomentumBegin`
-
- `onMomentumEnd`
-
-
Each key should map to an individual worklet function. These functions are triggered when the associated events occur on a connected Scrollable component.
-
-
The event worklets receive two parameters:
-
-
- `event`: An object containing information about the scroll. The structure of this payload varies based on the event type. Refer to React Native's ScrollView documentation for details.
-
-
- `context`: A plain JavaScript object used for storing state that persists between scroll events. This allows communication between multiple event handlers when provided as an object of worklets.
-
-
##### `dependencies` (Optional)
-
-
An optional array of dependencies, relevant only when using Reanimated without the Babel plugin on the Web.
-
-
#### Returns
-
-
The hook returns a handler object suitable for integration with a scrollable container. The returned handler should be assigned to the `onScroll` parameter, regardless of whether it is configured to handle scroll, momentum, or drag events. For proper functionality, use containers wrapped with `Animated`, such as `Animated.ScrollView`.
-
-
### Example
-
-
### Remarks
-
-
- The returned handler can be passed to multiple components. It will invoke for the specified events whenever any component dispatches them.
-
- If a single worklet function of type `(event) => void` is provided instead of an object mapping functions to event keys, it is treated as a handler for the `onScroll` event.
-
- Only the `onScroll` event is supported on Web.
-
-
### Platform Compatibility
-
-
|Android|iOS|Web|
-
|-|-|-|
-
|✅|✅|✅|
-
-
## useEvent Hook Overview
-
-
The `useEvent` hook is a foundational tool in React Native Reanimated that provides an event handler for native events. It's particularly useful for creating custom hooks like `useScrollViewOffset` or `useAnimatedScrollHandler`.
-
-
### Reference Usage
-
-
```typescript
-
import { useEvent } from 'react-native-reanimated';
-
-
function useAnimatedPagerScrollHandler(handlers, dependencies) {
-
const { context, doDependenciesDiffer } = useHandler(handlers, dependencies);
-
-
return useEvent(
-
(event) => {
-
'worklet';
-
const { onPageScroll } = handlers;
-
-
if (onPageScroll && event.eventName.endsWith('onPageScroll')) {
-
onPageScroll(event, context);
-
}
-
},
-
['onPageScroll'],
-
doDependenciesDiffer
+
function Two({ navigation }) {
+
return (
+
<>
+
<Animated.View sharedTransitionTag="sharedTag" />
+
<Button title="One" onPress={() => navigation.navigate('One')} />
+
</>
);
}
-
return <Animated.View onScroll={useAnimatedPagerScrollHandler} />;
+
export default function SharedElementExample() {
+
return (
+
<NavigationContainer>
+
<Stack.Navigator screenOptions={{ headerShown: true }}>
+
<Stack.Screen name="One" component={One} />
+
<Stack.Screen name="Two" component={Two} />
+
</Stack.Navigator>
+
</NavigationContainer>
+
);
+
}
```
-
#### Arguments
-
-
- **`handler`**: A function that receives an event object containing the native payload. This can be utilized within custom handler hooks' worklets.
-
-
- `event`: The event object, whose payload varies based on the event type.
-
-
- **`eventNames` (Optional)**: An array specifying which event names should trigger the handler.
+
### Overview
-
- **`rebuild` (Optional)**: A boolean indicating if the handler needs to be rebuilt.
+
When Reanimated detects a component with a `sharedTransitionTag` being mounted or unmounted, it searches for the last registered view with the same tag. If two matching components are found, their styles are captured and both views are temporarily moved to a transition container during the animation. Afterward, they return to their original parent.
-
#### Returns
+
Without custom animations, properties like `width`, `height`, `originX`, `originY`, and `transformMatrix` animate by default over 500ms using `withTiming`.
-
The hook returns an event handler that is invoked when a native event occurs. This handler can be connected to multiple components, triggering for each component's specific events.
+
### Implementation
-
### Example
+
To create a shared transition between components on different screens, assign the same `sharedTransitionTag`. Unique tags are required for multiple shared views on the same screen.
-
For simpler implementations, consider using `useScrollViewOffset`.
-
-
### Remarks
-
-
- Note that not all scroll events are supported on the web; only `onScroll` is consistently available across browsers.
-
-
### Platform Compatibility
-
-
|Android|iOS|Web|
-
|-|-|-|
-
|✅|✅|✅|
-
-
This overview provides a concise guide to using the `useEvent` hook effectively within React Native Reanimated projects.
-
-
## useHandler Hook in React Native Reanimated
-
-
The `useHandler` hook is a foundational tool within the React Native Reanimated library. It provides a context object and an indicator to determine if worklets require rebuilding. This functionality facilitates the creation of custom event handler hooks, such as `useScrollViewOffset` or `useAnimatedScrollHandler`.
-
-
### Reference
+
**Screen A**
```typescript
-
import { useEvent, useHandler } from "react-native-reanimated"
-
-
function useAnimatedPagerScrollHandler(
-
handlers: Record<string, (event: any, context: object) => void>,
-
dependencies?: any[]
-
) {
-
const { context, doDependenciesDiffer, useWeb } = useHandler(
-
handlers,
-
dependencies
-
)
-
-
return useEvent(
-
(event: any) => {
-
"worklet"
-
const { onPageScroll } = handlers
-
-
if (onPageScroll && event.eventName.endsWith("onPageScroll")) {
-
onPageScroll(event, context)
-
}
-
},
-
["onPageScroll"],
-
doDependenciesDiffer
-
)
-
}
+
<View
+
sharedTransitionTag="sharedTag"
+
style={{ width: 150, height: 150, backgroundColor: 'green' }}
+
/>
```
-
#### Arguments
+
**Screen B**
-
##### `handlers`
+
```typescript
+
<View
+
sharedTransitionTag="sharedTag"
+
style={{ width: 100, height: 100, backgroundColor: 'green' }}
+
/>
+
```
-
An object containing keys that correspond to native event names. The values should be individual worklets. Each worklet is triggered when its associated event is dispatched on the connected animated component.
+
### Custom Animation
-
Each event worklet receives:
+
Custom animations can be created using `SharedTransition.custom` for regular animations or `SharedTransition.progressAnimation` for progress-based ones.
-
- `event`: An event object whose payload varies based on the event type.
-
- `context`: A plain JavaScript object for storing state, persisting between events. This allows communication among multiple event handlers provided as an object of worklets.
+
```typescript
+
import { SharedTransition } from "react-native-reanimated"
-
##### `dependencies` (Optional)
-
-
An optional array of dependencies. This is relevant when using Reanimated without its Babel plugin in a web environment.
-
-
#### Returns
-
-
The hook returns:
-
-
- A context reused by event handlers.
-
- An indicator to determine if worklets should be rebuilt.
-
- A boolean, `useWeb`, to check for the web environment if different implementations are needed.
-
-
### Example
+
const transition = SharedTransition.custom((values) => {
+
"worklet"
+
return {
+
height: withSpring(values.targetHeight),
+
width: withSpring(values.targetWidth),
+
}
+
})
+
.progressAnimation((values, progress) => {
+
"worklet"
+
const getValue = (
+
progress: number,
+
target: number,
+
current: number
+
): number => {
+
return progress * (target - current) + current
+
}
+
return {
+
width: getValue(progress, values.targetWidth, values.currentWidth),
+
height: getValue(progress, values.targetHeight, values.currentHeight),
+
}
+
})
+
.defaultTransitionType(SharedTransitionType.ANIMATION)
+
```
-
For simpler implementations, consider using `useScrollViewOffset`.
+
By setting `defaultTransitionType(SharedTransitionType.ANIMATION)`, the custom animation is used for screen transitions, while progress-based animations apply during swipe-back gestures (iOS only). Use `defaultTransitionType(SharedTransitionType.PROGRESS_ANIMATION)` to apply progress-based animations in both scenarios.
-
### Platform Compatibility
-
-
|Android|iOS|Web|
-
|-|-|-|
-
|✅|✅|✅|
-
-
This documentation provides a comprehensive overview of how to utilize the `useHandler` hook within React Native Reanimated for creating custom event handlers.
-
-
## Keyframe Animations
-
-
Keyframes provide a schema for defining animations, offering more flexibility than standard Entering and Exiting presets. They allow you to create complex animations with ease.
-
-
### Reference
+
To use a custom animation, pass it as `sharedTransitionStyle` to components. Different animations can be assigned to different components sharing the same tag for directional transitions.
```typescript
-
import { Keyframe } from 'react-native-reanimated';
-
-
const keyframe = new Keyframe({
-
0: {
-
transform: [{ rotate: '0deg' }],
-
},
-
45: {
-
transform: [{ rotate: '100deg' }],
-
easing: Easing.exp,
-
},
-
100: {
-
transform: [{ rotate: '45deg' }],
-
},
-
});
-
-
function App() {
-
return <Animated.View entering={keyframe} />;
-
}
+
<View
+
sharedTransitionTag="reanimatedTransition"
+
sharedTransitionStyle={transition}
+
style={{ backgroundColor: 'blue', width: 200, height: 100 }}
+
/>
```
-
#### Arguments
-
-
##### `definitions`
-
-
An object containing animation definitions. The keys should be within the range of `0-100`, representing the progress of the animation. Values consist of style properties and optionally an easing function, defaulting to `Easing.linear` if not specified.
-
-
Key values include:
+
### Example
-
- `0` or `from`: Represents the initial state.
-
- Intermediate points (e.g., `45`): Represent intermediate states.
-
- `100` or `to`: Represents the final state.
+
Your browser does not support the video tag.
-
The key `0` (or `from`) should define the style at the start of the animation, while `100` (or `to`) defines it at the end.
+
Your browser does not support the video tag.
-
### Modifiers
+
Expand the full code:
```typescript
-
keyframe
-
.duration(1000)
-
.delay(500)
-
.reduceMotion(ReduceMotion.Never)
-
.withCallback((finished) => {
-
console.log(`finished without interruptions: ${finished}`)
-
})
+
<Pressable onPress={() => goToDetails('countryside')}>
+
<Animated.View
+
sharedTransitionTag={'countryside'}
+
style={[
+
styles.imageOne,
+
{ backgroundColor: gallery.countryside.color },
+
]}
+
/>
+
</Pressable>
+
<View style={styles.row}>
+
<Pressable onPress={() => goToDetails('florence')}>
+
<Animated.View
+
sharedTransitionTag={'florence'}
+
style={[
+
{ width: width / 2 - 35 },
+
styles.imageTwo,
+
{ backgroundColor: gallery.florence.color },
+
]}
+
/>
+
</Pressable>
+
<Pressable onPress={() => goToDetails('dawn')}>
+
<Animated.View
+
sharedTransitionTag={'dawn'}
+
style={[
+
{ width: width / 2 - 35 },
+
styles.imageThree,
+
{ backgroundColor: gallery.dawn.color },
+
]}
+
/>
+
</Pressable>
+
</View>
```
-
- `.duration(durationMs: number)` sets the animation length in milliseconds, defaulting to `500`.
-
- `.delay(durationMs: number)` specifies a delay before starting the animation, defaulting to `0`.
-
- `.reduceMotion(reduceMotion: ReduceMotion)` adjusts the animation based on the device's reduced motion setting.
-
- `.withCallback(callback: (finished: boolean) => void)` triggers after the animation ends, indicating if it finished without interruptions.
-
### Remarks
-
- Providing keyframe `0` or `from` is mandatory as it defines the initial state of the object to be animated.
-
- Ensure all style properties intended for animation have an initial value in other keyframes.
-
- Easing should only be applied to subsequent keyframes, not to keyframe `0`.
-
- Avoid using both `0` and `from`, or `100` and `to`, as it causes parsing conflicts.
-
- When animating transform styles, maintain the order of properties consistently across all keyframes.
+
- Only the native stack is supported.
+
- Animatable properties include `width`, `height`, `originX`, `originY`, and `transformMatrix`.
+
- Layout for shared view children isn't computed during transitions.
+
- Currently supports only the old React Native architecture (Paper).
+
- Future support for the new React Native architecture (Fabric) is planned.
### Platform Compatibility
|Android|iOS|Web|
|-|-|-|
-
|✅|✅|✅|
+
|✅|✅|❌|
## Troubleshooting
···
For more information, refer to Reanimated's documentation on worklets.
-
## Shared Element Transitions
-
-
> **Caution:**\
-
> Shared Element Transition is an experimental feature and not recommended for production use yet. Feedback is welcomed to enhance its implementation.
-
-
Shared Element Transition enables a smooth transformation of a component from one screen to another.
-
-
### Reference
-
-
```typescript
-
import Animated from 'react-native-reanimated';
-
-
const Stack = createNativeStackNavigator();
-
-
function One({ navigation }) {
-
return (
-
<>
-
<Animated.View sharedTransitionTag="sharedTag" />
-
<Button title="Two" onPress={() => navigation.navigate('Two')} />
-
</>
-
);
-
}
-
-
function Two({ navigation }) {
-
return (
-
<>
-
<Animated.View sharedTransitionTag="sharedTag" />
-
<Button title="One" onPress={() => navigation.navigate('One')} />
-
</>
-
);
-
}
-
-
export default function SharedElementExample() {
-
return (
-
<NavigationContainer>
-
<Stack.Navigator screenOptions={{ headerShown: true }}>
-
<Stack.Screen name="One" component={One} />
-
<Stack.Screen name="Two" component={Two} />
-
</Stack.Navigator>
-
</NavigationContainer>
-
);
-
}
-
```
-
-
### Overview
-
-
When Reanimated detects a component with a `sharedTransitionTag` being mounted or unmounted, it searches for the last registered view with the same tag. If two matching components are found, their styles are captured and both views are temporarily moved to a transition container during the animation. Afterward, they return to their original parent.
-
-
Without custom animations, properties like `width`, `height`, `originX`, `originY`, and `transformMatrix` animate by default over 500ms using `withTiming`.
-
-
### Implementation
-
-
To create a shared transition between components on different screens, assign the same `sharedTransitionTag`. Unique tags are required for multiple shared views on the same screen.
-
-
**Screen A**
-
-
```typescript
-
<View
-
sharedTransitionTag="sharedTag"
-
style={{ width: 150, height: 150, backgroundColor: 'green' }}
-
/>
-
```
-
-
**Screen B**
-
-
```typescript
-
<View
-
sharedTransitionTag="sharedTag"
-
style={{ width: 100, height: 100, backgroundColor: 'green' }}
-
/>
-
```
-
-
### Custom Animation
-
-
Custom animations can be created using `SharedTransition.custom` for regular animations or `SharedTransition.progressAnimation` for progress-based ones.
-
-
```typescript
-
import { SharedTransition } from "react-native-reanimated"
-
-
const transition = SharedTransition.custom((values) => {
-
"worklet"
-
return {
-
height: withSpring(values.targetHeight),
-
width: withSpring(values.targetWidth),
-
}
-
})
-
.progressAnimation((values, progress) => {
-
"worklet"
-
const getValue = (
-
progress: number,
-
target: number,
-
current: number
-
): number => {
-
return progress * (target - current) + current
-
}
-
return {
-
width: getValue(progress, values.targetWidth, values.currentWidth),
-
height: getValue(progress, values.targetHeight, values.currentHeight),
-
}
-
})
-
.defaultTransitionType(SharedTransitionType.ANIMATION)
-
```
-
-
By setting `defaultTransitionType(SharedTransitionType.ANIMATION)`, the custom animation is used for screen transitions, while progress-based animations apply during swipe-back gestures (iOS only). Use `defaultTransitionType(SharedTransitionType.PROGRESS_ANIMATION)` to apply progress-based animations in both scenarios.
-
-
To use a custom animation, pass it as `sharedTransitionStyle` to components. Different animations can be assigned to different components sharing the same tag for directional transitions.
-
-
```typescript
-
<View
-
sharedTransitionTag="reanimatedTransition"
-
sharedTransitionStyle={transition}
-
style={{ backgroundColor: 'blue', width: 200, height: 100 }}
-
/>
-
```
-
-
### Example
-
-
Your browser does not support the video tag.
-
-
Your browser does not support the video tag.
-
-
Expand the full code:
-
-
```typescript
-
<Pressable onPress={() => goToDetails('countryside')}>
-
<Animated.View
-
sharedTransitionTag={'countryside'}
-
style={[
-
styles.imageOne,
-
{ backgroundColor: gallery.countryside.color },
-
]}
-
/>
-
</Pressable>
-
<View style={styles.row}>
-
<Pressable onPress={() => goToDetails('florence')}>
-
<Animated.View
-
sharedTransitionTag={'florence'}
-
style={[
-
{ width: width / 2 - 35 },
-
styles.imageTwo,
-
{ backgroundColor: gallery.florence.color },
-
]}
-
/>
-
</Pressable>
-
<Pressable onPress={() => goToDetails('dawn')}>
-
<Animated.View
-
sharedTransitionTag={'dawn'}
-
style={[
-
{ width: width / 2 - 35 },
-
styles.imageThree,
-
{ backgroundColor: gallery.dawn.color },
-
]}
-
/>
-
</Pressable>
-
</View>
-
```
-
-
### Remarks
-
-
- Only the native stack is supported.
-
- Animatable properties include `width`, `height`, `originX`, `originY`, and `transformMatrix`.
-
- Layout for shared view children isn't computed during transitions.
-
- Currently supports only the old React Native architecture (Paper).
-
- Future support for the new React Native architecture (Fabric) is planned.
-
-
### Platform Compatibility
-
-
|Android|iOS|Web|
-
|-|-|-|
-
|✅|✅|❌|
-
## useAnimatedScrollHandler
The `useAnimatedScrollHandler` hook provides an event handler reference that can be utilized with React Native's scrollable components. This hook is part of the `react-native-reanimated` library.
···
|-|-|-|
|✅|✅|✅|
-
## scrollTo Function in React Native Reanimated
+
## useAnimatedScrollHandler
-
The `scrollTo` function allows you to synchronously scroll a component to a specified X or Y offset.
+
The `useAnimatedScrollHandler` hook provides an event handler reference that can be utilized with React Native's scrollable components. This hook is part of the `react-native-reanimated` library.
### Reference
```typescript
-
import { scrollTo } from 'react-native-reanimated';
+
import { useAnimatedScrollHandler } from 'react-native-reanimated';
function App() {
-
const animatedRef = useAnimatedRef();
-
const scrollY = useSharedValue(0);
+
const offsetY = useSharedValue(0);
-
useDerivedValue(() => {
-
scrollTo(animatedRef, 0, scrollY.value, true);
+
const scrollHandler = useAnimatedScrollHandler((event) => {
+
offsetY.value = event.contentOffset.y;
});
-
return (
-
<Animated.ScrollView ref={animatedRef}>{/* ... */}</Animated.ScrollView>
-
);
+
// ...
+
+
return <Animated.ScrollView onScroll={scrollHandler} />;
}
```
#### Arguments
-
- **`animatedRef`**: An animated reference linked to the ScrollView (or another scrollable) component you wish to scroll. This animated reference must be passed to either an Animated component or a React Native built-in component.
-
-
- **`x`**: The pixel value for horizontal scrolling on the X axis.
-
-
- **`y`**: The pixel value for vertical scrolling on the Y axis.
-
-
- **`animated`**: A boolean indicating if the scroll should be smooth (`true`) or instant (`false`).
-
-
#### Returns
-
-
The `scrollTo` function returns `undefined`.
-
-
### Remarks
-
-
- The `scrollTo` function must be invoked from the UI thread.
-
- It supports `Animated.FlatList`.
-
- Typically works with other ScrollView-like and FlatList-like components if they use a `ScrollView` internally and are animated.
-
- Scrollable components need to implement the `getScrollableNode` method (and `getNativeScrollRef` for New Architecture) to be compatible with `scrollTo`.
-
-
### Platform Compatibility
-
-
|Android|iOS|Web|
-
|-|-|-|
-
|✅|✅|✅|
-
-
## getRelativeCoords Functionality
-
-
The `getRelativeCoords` function is used to determine the screen location relative to a specified view.
-
-
### Reference Code
-
-
```typescript
-
import { getRelativeCoords } from 'react-native-reanimated';
-
-
const Comp = () => {
-
const animatedRef = useAnimatedRef();
-
-
const gestureHandler = useAnimatedGestureHandler({
-
onEnd: (event) => {
-
const coords = getRelativeCoords(
-
animatedRef,
-
event.absoluteX,
-
event.absoluteY
-
);
-
},
-
});
-
-
return (
-
<View ref={animatedRef}>
-
<PanGestureHandler onGestureEvent={gestureHandler}>
-
<Animated.View style={[styles.box]} />
-
</PanGestureHandler>
-
</View>
-
);
-
};
-
```
-
-
### Arguments
-
-
- **`animatedRef`**: This is the result of `useAnimatedRef`, which extends a standard React ref to deliver the view tag on the UI thread. It should be passed as a prop to the view relative to which coordinates are needed.
+
##### `handlers`
-
- **`absoluteX`**: A number representing the absolute x-coordinate.
+
An object containing custom keys that correspond to native event names. Available keys include:
-
- **`absoluteY`**: A number representing the absolute y-coordinate.
-
-
### Returns
-
-
An object containing:
-
-
- `x`: The relative x-coordinate.
-
- `y`: The relative y-coordinate.
+
- `onScroll`
+
- `onBeginDrag`
+
- `onEndDrag`
+
- `onMomentumBegin`
+
- `onMomentumEnd`
-
### Platform Compatibility
+
Each key should map to an individual worklet function. These functions are triggered when the associated events occur on a connected Scrollable component.
-
|Android|iOS|Web|
-
|-|-|-|
-
|✅|✅|✅|
+
The event worklets receive two parameters:
-
## useAnimatedGestureHandler
+
- `event`: An object containing information about the scroll. The structure of this payload varies based on the event type. Refer to React Native's ScrollView documentation for details.
-
**Warning:**\
-
The `useAnimatedGestureHandler` hook allows for the creation of animations based on gesture handlers. It is essential to provide the object created by this hook to the `onGestureEvent` property of a gesture handler component.
-
-
This hook necessitates that `react-native-gesture-handler` be installed and configured within your project.
-
-
### Reference
-
-
```typescript
-
import { useAnimatedGestureHandler } from 'react-native-reanimated';
-
import { PanGestureHandler } from 'react-native-gesture-handler';
-
-
function App() {
-
const x = useSharedValue(0);
-
-
const gestureHandler = useAnimatedGestureHandler({
-
onStart: (_, ctx) => {
-
ctx.startX = x.value;
-
},
-
onActive: (event, ctx) => {
-
x.value = ctx.startX + event.translationX;
-
},
-
});
-
-
return (
-
<PanGestureHandler onGestureEvent={gestureHandler}>
-
<Animated.View />
-
</PanGestureHandler>
-
);
-
}
-
```
-
-
#### Arguments
-
-
##### `gestureHandlers`
-
-
The primary argument is an object that can include one or more handlers. These handlers are set under the following keys: `onStart`, `onActive`, `onEnd`, `onFail`, `onCancel`, and `onFinish`.
-
-
Each handler will be activated based on the current state of the associated gesture handler. For further details, refer to the Gesture Handler documentation. The handler receives:
-
-
- `event` \[object] - an event object containing the payload specific to the type of gesture handler (e.g., `PanGestureHandler`, `RotationGestureHandler`).
-
-
- `context` \[object] - a JavaScript object for storing state information. This context can be read and modified, persisting between events and across handlers for all selected states.
+
- `context`: A plain JavaScript object used for storing state that persists between scroll events. This allows communication between multiple event handlers when provided as an object of worklets.
##### `dependencies` (Optional)
-
An optional array of dependencies is relevant only when using Reanimated without the Babel plugin on the Web.
+
An optional array of dependencies, relevant only when using Reanimated without the Babel plugin on the Web.
#### Returns
-
The `useAnimatedGestureHandler` hook returns a handler object that can be attached to gesture handler components from the `react-native-gesture-handler` library. This object must be passed to the `onGestureEvent` property of a gesture handler component.
+
The hook returns a handler object suitable for integration with a scrollable container. The returned handler should be assigned to the `onScroll` parameter, regardless of whether it is configured to handle scroll, momentum, or drag events. For proper functionality, use containers wrapped with `Animated`, such as `Animated.ScrollView`.
### Example
-
### Platform Compatibility
-
-
|Android|iOS|Web|
-
|-|-|-|
-
|✅|✅|⚠️|
-
-
- On the Web, it is necessary to pass the returned handler object to both `onGestureEvent` and `onHandlerStateChange` parameters.
-
-
## useScrollViewOffset Hook
-
-
The `useScrollViewOffset` hook enables the creation of animations based on a `ScrollView`'s offset. It automatically determines whether the `ScrollView` is oriented horizontally or vertically.
-
-
### Reference
+
### Remarks
-
```typescript
-
import { useAnimatedRef, useScrollViewOffset } from 'react-native-reanimated';
-
-
function App() {
-
const animatedRef = useAnimatedRef();
-
const scrollOffset = useScrollViewOffset(animatedRef);
-
-
return (
-
<Animated.ScrollView ref={animatedRef}>
-
{/* Content goes here */}
-
</Animated.ScrollView>
-
);
-
}
-
```
-
-
#### Arguments
-
-
##### `animatedRef`
-
-
An animated reference linked to the `ScrollView` component you wish to monitor. This animated reference must be assigned either to an Animated component or a React Native built-in component.
-
-
##### `initialRef` (Optional)
-
-
A shared value that can optionally be updated with the scroll offset. If not provided, a new shared value will be created internally by default.
-
-
#### Returns
-
-
The hook returns a shared value representing the current offset of the `ScrollView`.
-
-
### Example Usage
-
-
- The `animatedRef` argument can be dynamically changed, and the hook will continue to provide accurate values based on the connected `ScrollView`. For instance:
-
-
```typescript
-
useScrollViewOffset(someState ? someScrollRefA : someScrollRefB)
-
```
+
- The returned handler can be passed to multiple components. It will invoke for the specified events whenever any component dispatches them.
+
- If a single worklet function of type `(event) => void` is provided instead of an object mapping functions to event keys, it is treated as a handler for the `onScroll` event.
+
- Only the `onScroll` event is supported on Web.
### Platform Compatibility
···
|-|-|-|
|✅|✅|✅|
-
```markdown
-
# Advanced APIs - Version 3.x
-
-
## measure
-
-
`measure` allows synchronous retrieval of a view's dimensions and position on the screen, executed on the UI thread.
-
-
## useAnimatedReaction
-
-
`useAnimatedReaction` enables response to changes in a shared value. It is particularly useful for comparing previous values stored in the shared value with their current counterparts.
-
-
## useFrameCallback
-
-
`useFrameCallback` facilitates running a function during each frame update.
-
## useEvent
-
`useEvent` is a foundational hook that returns an event handler triggered by native events. This can be utilized to create custom event handler hooks, such as `useScrollViewOffset` or `useAnimatedScrollHandler`.
+
The `useEvent` hook is a foundational tool in React Native Reanimated that provides an event handler for native events. It's particularly useful for creating custom hooks like `useScrollViewOffset` or `useAnimatedScrollHandler`.
-
## useHandler
-
-
`useHandler` is another fundamental hook providing a context object and a value indicating if the worklet requires rebuilding. It aids in creating custom event handler hooks like `useScrollViewOffset` or `useAnimatedScrollHandler`.
-
-
## useComposedEventHandler
-
-
This hook allows for the composition of `useEvent`-based event handlers (e.g., `useAnimatedScrollHandler` or custom ones) into a single, unified event handler.
-
-
## dispatchCommand
-
-
`dispatchCommand` enables execution of commands on a native component directly from the UI thread.
-
-
## setNativeProps
-
-
`setNativeProps` allows for imperative updates to component properties.
-
-
## makeMutable
-
-
The use of `makeMutable` is generally discouraged. It's advised to opt for the `useSharedValue` hook unless you are fully aware of its implications and consequences (refer to the Remarks section).
-
```
-
-
## Handling Gestures
-
-
This section covers handling gestures using Reanimated in conjunction with React Native Gesture Handler. We'll focus on `Tap` and `Pan` gestures and introduce the `withDecay` animation function.
-
-
Ensure you've completed the Gesture Handler installation steps before proceeding.
-
-
### Handling Tap Gestures
-
-
We begin with tap gestures, which detect brief screen touches. These can be used for custom buttons or pressable elements.
-
-
In this example, a circle grows and changes color upon touch.
-
-
First, wrap your app in `GestureHandlerRootView` to ensure gesture functionality:
+
### Reference Usage
```typescript
-
import { GestureHandlerRootView } from 'react-native-gesture-handler';
-
-
function App() {
-
return (
-
<GestureHandlerRootView style={{ flex: 1 }}>
-
{/* rest of the app */}
-
</GestureHandlerRootView>
-
);
-
}
-
```
-
-
Define tap gestures using `Gesture.Tap()` and chain methods like `onBegin`, `onStart`, `onEnd`, or `onFinalize` to update shared values:
-
-
```typescript
-
export default function App() {
-
const pressed = useSharedValue<boolean>(false);
-
-
const tap = Gesture.Tap()
-
.onBegin(() => {
-
pressed.value = true;
-
})
-
.onFinalize(() => {
-
pressed.value = false;
-
});
-
```
+
import { useEvent } from 'react-native-reanimated';
-
Access shared values safely as gesture callbacks are automatically workletized.
+
function useAnimatedPagerScrollHandler(handlers, dependencies) {
+
const { context, doDependenciesDiffer } = useHandler(handlers, dependencies);
-
Define animation logic using `withTiming` in `useAnimatedStyle`:
+
return useEvent(
+
(event) => {
+
'worklet';
+
const { onPageScroll } = handlers;
-
```typescript
-
const animatedStyles = useAnimatedStyle(() => ({
-
backgroundColor: pressed.value ? "#FFE04B" : "#B58DF1",
-
transform: [{ scale: withTiming(pressed.value ? 1.2 : 1) }],
-
}))
-
```
-
-
Pass the gesture to `GestureDetector` and apply `animatedStyles`:
-
-
```typescript
-
return (
-
<GestureHandlerRootView style={styles.container}>
-
<View style={styles.container}>
-
<GestureDetector gesture={tap}>
-
<Animated.View style={[styles.circle, animatedStyles]} />
-
</GestureDetector>
-
</View>
-
</GestureHandlerRootView>
+
if (onPageScroll && event.eventName.endsWith('onPageScroll')) {
+
onPageScroll(event, context);
+
}
+
},
+
['onPageScroll'],
+
doDependenciesDiffer
);
}
-
```
-
### Handling Pan Gestures
-
-
Enhance the circle by making it draggable and bouncing back to its starting position upon release. Retain color highlight and scale effects.
-
-
Switch from `Tap` to `Pan` gesture and add an `onChange` method:
-
-
```typescript
-
const offset = useSharedValue<number>(0);
-
-
const pan = Gesture.Pan()
-
.onBegin(() => {
-
pressed.value = true;
-
})
-
.onChange((event) => {
-
offset.value = event.translationX;
-
})
-
.onFinalize(() => {
-
offset.value = withSpring(0);
-
pressed.value = false;
-
```
-
-
Use `translationX` from the event data to move the circle. Reset `offset.value` in `onFinalize` using `withSpring`.
-
-
Adjust `useAnimatedStyle` for handling offset:
-
-
```typescript
-
const animatedStyles = useAnimatedStyle(() => ({
-
transform: [
-
{ translateX: offset.value },
-
{ scale: withTiming(pressed.value ? 1.2 : 1) },
-
],
-
backgroundColor: pressed.value ? "#FFE04B" : "#b58df1",
-
}))
-
```
-
-
### Using `withDecay`
-
-
`withDecay` retains gesture velocity for decelerating animations.
-
-
Pass final velocity in `onFinalize` to `withDecay`:
-
-
```typescript
-
const pan = Gesture.Pan()
-
.onChange((event) => {
-
offset.value += event.changeX;
-
})
-
.onFinalize((event) => {
-
offset.value = withDecay({
-
velocity: event.velocityX,
-
rubberBandEffect: true,
-
clamp: [
-
-(width.value / 2) + SIZE / 2 + BOUNDARY_OFFSET,
-
width.value / 2 - SIZE / 2 - BOUNDARY_OFFSET,
-
```
-
-
Ensure the square stays within screen bounds.
-
-
Explore `withDecay` API for more configuration options.
-
-
### Summary
-
-
This section covered gesture handling with Reanimated and Gesture Handler, focusing on `Tap`, `Pan`, and `withDecay`. Key points include:
-
-
- Integration of Reanimated with React Native Gesture Handler.
-
- Creation of gestures like `Gesture.Pan()` or `Gesture.Tap()`.
-
- Accessing shared values in gesture callbacks without extra boilerplate.
-
- Using `withDecay` for decelerating animations based on gesture velocity.
-
-
### What's Next?
-
-
Explore further gestures such as Pinch and Fling by reviewing the React Native Gesture Handler documentation. The next section will delve into a glossary of terms.
-
-
## withRepeat
-
-
`withRepeat` is an animation modifier that allows you to repeat a specified animation a certain number of times or indefinitely.
-
-
### Reference
-
-
```typescript
-
import { withRepeat } from "react-native-reanimated"
-
-
function App() {
-
sv.value = withRepeat(withSpring(0), 5)
-
// ...
-
}
+
return <Animated.View onScroll={useAnimatedPagerScrollHandler} />;
```
#### Arguments
-
##### `animation`
+
- **`handler`**: A function that receives an event object containing the native payload. This can be utilized within custom handler hooks' worklets.
-
The animation object you wish to repeat.
+
- `event`: The event object, whose payload varies based on the event type.
-
##### `numberOfReps` (Optional)
+
- **`eventNames` (Optional)**: An array specifying which event names should trigger the handler.
-
Specifies how many times the animation should be repeated. The default is `2`.
+
- **`rebuild` (Optional)**: A boolean indicating if the handler needs to be rebuilt.
-
A non-positive value, such as `0` or `-1`, will cause the animation to repeat indefinitely until it is canceled or removed. For instance, if the component unmounts or `cancelAnimation` is invoked.
+
#### Returns
-
##### `reverse` (Optional)
+
The hook returns an event handler that is invoked when a native event occurs. This handler can be connected to multiple components, triggering for each component's specific events.
-
Determines whether the animation should alternate directions with each repetition. The default setting is `false`.
-
-
This feature only supports direct animation functions like `withSpring` and does not work with other animation modifiers such as `withSequence`.
-
-
##### `callback` (Optional)
-
-
A function that executes upon the completion of the animation. If the animation is canceled, the callback receives `false`; otherwise, it receives `true`.
-
-
##### `reduceMotion` (Optional)
-
-
Controls how the animation responds to the device's reduced motion accessibility setting.
-
-
#### Returns
+
### Example
-
The `withRepeat` function returns an animation object representing the current state of the animation. This can be directly assigned to a shared value or used as a style object returned from `useAnimatedStyle`.
+
For simpler implementations, consider using `useScrollViewOffset`.
### Remarks
-
- The callback provided in the fourth argument is automatically workletized and executed on the UI thread.
+
- Note that not all scroll events are supported on the web; only `onScroll` is consistently available across browsers.
### Platform Compatibility
···
|-|-|-|
|✅|✅|✅|
-
## Measure Functionality in React Native Reanimated
+
This overview provides a concise guide to using the `useEvent` hook effectively within React Native Reanimated projects.
+
+
## useHandler
-
The `measure` function allows you to synchronously obtain the dimensions and position of a view on the screen, executed on the UI thread.
+
The `useHandler` hook is a foundational tool within the React Native Reanimated library. It provides a context object and an indicator to determine if worklets require rebuilding. This functionality facilitates the creation of custom event handler hooks, such as `useScrollViewOffset` or `useAnimatedScrollHandler`.
### Reference
```typescript
-
import { measure } from 'react-native-reanimated';
+
import { useEvent, useHandler } from "react-native-reanimated"
-
function App() {
-
const animatedRef = useAnimatedRef();
+
function useAnimatedPagerScrollHandler(
+
handlers: Record<string, (event: any, context: object) => void>,
+
dependencies?: any[]
+
) {
+
const { context, doDependenciesDiffer, useWeb } = useHandler(
+
handlers,
+
dependencies
+
)
-
const handlePress = () => {
-
runOnUI(() => {
-
const measurement = measure(animatedRef);
-
if (measurement === null) {
-
return;
-
}
-
// Additional logic can be added here
-
})();
-
};
-
-
return <Animated.View ref={animatedRef} />;
-
}
-
```
-
-
#### Arguments
-
-
- **`animatedRef`**: An animated reference linked to the component whose measurements are desired. This reference must be associated with either an Animated component or a React Native built-in component.
-
-
#### Returns
-
-
The `measure` function returns an object containing:
-
-
|Field|Description|
-
|-|-|
-
|`x`|A number representing the X coordinate relative to the parent component.|
-
|`y`|A number representing the Y coordinate relative to the parent component.|
-
|`width`|A number representing the width of the component.|
-
|`height`|A number representing the height of the component.|
-
|`pageX`|A number representing the X coordinate relative to the screen.|
-
|`pageY`|A number representing the Y coordinate relative to the screen.|
-
-
Alternatively, it returns `null` if the measurement could not be performed.
+
return useEvent(
+
(event: any) => {
+
"worklet"
+
const { onPageScroll } = handlers
-
### Remarks
-
-
- **UI Thread Execution**: The `measure` function operates exclusively on the UI thread. When used within event handlers, it must be wrapped with the `runOnUI` function.
-
-
- **Use in `useAnimatedStyle`**: Since `useAnimatedStyle` is initially evaluated on the JavaScript thread before views are attached to the native side, a condition like the following should be included:
-
-
```typescript
-
function App() {
-
const animatedStyles = useAnimatedStyle(() => {
-
if (_WORKLET) {
-
// Safely use measure here
-
const measurement = measure(animatedRef)
-
}
-
})
-
}
-
```
-
-
- **Consecutive Runs**: Subsequent executions of `useAnimatedStyle` occur on the UI thread.
-
-
- **Alternative for Static Dimensions**: If only static dimensions are needed and measurements aren't used during animations, consider using the `onLayout` property instead.
-
-
- **Null Check**: It's advisable to check if the measurement result is `null`, as it may happen when the reference hasn't yet attached to a view:
-
-
```typescript
-
const animatedRef = useAnimatedRef()
-
-
const handlePress = () => {
-
runOnUI(() => {
-
const measurement = measure(animatedRef)
-
-
if (measurement === null) {
-
return
-
}
-
// Additional logic can be added here
-
})()
-
}
-
```
-
-
- **Rendered Components Only**: `measure` is applicable only to rendered components. For example, measuring off-screen items in a `FlatList` will yield `null`.
-
-
- **Debugger Compatibility**: The `measure` function isn't available with the Remote JS Debugger. It's recommended to use Chrome DevTools (`chrome://inspect`) for debugging React Native applications.
-
-
### Platform Compatibility
-
-
|Android|iOS|Web|
-
|-|-|-|
-
|✅|✅|✅|
-
-
## useAnimatedReaction
-
-
The `useAnimatedReaction` hook enables responses to changes in shared values, particularly useful when comparing previous and current values stored within a shared value.
-
-
### Reference
-
-
```typescript
-
import { useAnimatedReaction } from "react-native-reanimated"
-
-
function App() {
-
useAnimatedReaction(
-
() => sv.value,
-
(currentValue, previousValue) => {
-
if (currentValue !== previousValue) {
-
// perform an action ✨
+
if (onPageScroll && event.eventName.endsWith("onPageScroll")) {
+
onPageScroll(event, context)
}
-
}
+
},
+
["onPageScroll"],
+
doDependenciesDiffer
)
-
-
// ...
}
```
#### Arguments
-
##### `prepare`
+
##### `handlers`
-
A function returning the value to which you want to react. This returned value serves as the first parameter for the `react` argument.
+
An object containing keys that correspond to native event names. The values should be individual worklets. Each worklet is triggered when its associated event is dispatched on the connected animated component.
-
```typescript
-
function App() {
-
useAnimatedReaction(
-
() => Math.floor(sv.value),
-
(currentValue, previousValue) => {
-
// ...
-
}
-
)
-
}
-
```
+
Each event worklet receives:
-
##### `react`
-
-
A function that responds to changes in the value provided by the `prepare` function. It receives two parameters: the current value from `prepare` and the previous value, initially set to `null`.
-
-
```typescript
-
function App() {
-
useAnimatedReaction(
-
() => Math.floor(sv.value),
-
(currentValue, previousValue) => {
-
// ...
-
}
-
)
-
}
-
```
+
- `event`: An event object whose payload varies based on the event type.
+
- `context`: A plain JavaScript object for storing state, persisting between events. This allows communication among multiple event handlers provided as an object of worklets.
##### `dependencies` (Optional)
-
An optional array of dependencies. This is only relevant when using Reanimated without the Babel plugin on the Web.
+
An optional array of dependencies. This is relevant when using Reanimated without its Babel plugin in a web environment.
#### Returns
-
The `useAnimatedReaction` hook returns `undefined`.
+
The hook returns:
-
### Example
+
- A context reused by event handlers.
+
- An indicator to determine if worklets should be rebuilt.
+
- A boolean, `useWeb`, to check for the web environment if different implementations are needed.
-
### Remarks
+
### Example
-
- Avoid mutating the same shared value in the `react` function that was used in the `prepare` function to prevent infinite loops.
-
-
```typescript
-
function App() {
-
useAnimatedReaction(
-
() => width.value,
-
(currentValue) => {
-
// 🚨 An infinite loop!
-
width.value += currentValue
-
}
-
)
-
}
-
```
-
-
- Callbacks for both `prepare` and `react` are automatically workletized, running on the UI thread.
-
-
- While you can use `useAnimatedReaction` to react to any stateful React value, it's generally better to use a `useEffect` for such purposes.
+
For simpler implementations, consider using `useScrollViewOffset`.
### Platform Compatibility
···
|-|-|-|
|✅|✅|✅|
-
````markdown
-
# withSequence
+
This documentation provides a comprehensive overview of how to utilize the `useHandler` hook within React Native Reanimated for creating custom event handlers.
+
+
## Keyframe animations
-
`withSequence` is an animation modifier that allows animations to be executed in a sequential order.
+
Keyframes provide a schema for defining animations, offering more flexibility than standard Entering and Exiting presets. They allow you to create complex animations with ease.
-
## Reference
+
### Reference
```typescript
-
import { withSequence } from "react-native-reanimated"
+
import { Keyframe } from 'react-native-reanimated';
+
+
const keyframe = new Keyframe({
+
0: {
+
transform: [{ rotate: '0deg' }],
+
},
+
45: {
+
transform: [{ rotate: '100deg' }],
+
easing: Easing.exp,
+
},
+
100: {
+
transform: [{ rotate: '45deg' }],
+
},
+
});
function App() {
-
sv.value = withSequence(withTiming(50), withTiming(0))
-
// ...
+
return <Animated.View entering={keyframe} />;
}
```
-
````
#### Arguments
-
##### `reduceMotion` (Optional)
+
##### `definitions`
-
A parameter that specifies how the animation should respond to the device's reduced motion accessibility setting.
+
An object containing animation definitions. The keys should be within the range of `0-100`, representing the progress of the animation. Values consist of style properties and optionally an easing function, defaulting to `Easing.linear` if not specified.
-
##### `...animations`
+
Key values include:
-
Any number of animation objects that will be executed in sequence.
-
-
#### Returns
+
- `0` or `from`: Represents the initial state.
+
- Intermediate points (e.g., `45`): Represent intermediate states.
+
- `100` or `to`: Represents the final state.
-
The `withSequence` function returns an animation object representing the current state of the animation. This object can either be directly assigned to a shared value or used as a value for a style object returned from `useAnimatedStyle`.
+
The key `0` (or `from`) should define the style at the start of the animation, while `100` (or `to`) defines it at the end.
-
### Example
-
-
### Platform Compatibility
-
-
|Android|iOS|Web|
-
|-|-|-|
-
|✅|✅|✅|
-
-
````
-
-
# useFrameCallback in React Native Reanimated (Version: 3.x)
-
-
## Overview
-
-
The `useFrameCallback` hook allows you to execute a function on every frame update within your application.
-
-
## Reference
+
### Modifiers
```typescript
-
import { useFrameCallback } from 'react-native-reanimated';
+
keyframe
+
.duration(1000)
+
.delay(500)
+
.reduceMotion(ReduceMotion.Never)
+
.withCallback((finished) => {
+
console.log(`finished without interruptions: ${finished}`)
+
})
+
```
-
function App() {
-
const frameCallback = useFrameCallback((frameInfo) => {
-
// Increment a value with each frame update
-
sv.value += 1;
-
});
-
-
return (
-
<Button
-
title="Start/Stop"
-
onPress={() => frameCallback.setActive(!frameCallback.isActive)}
-
/>
-
);
-
}
-
````
-
-
#### Arguments
-
-
##### `callback`
-
-
- A function that runs on every frame update.
-
- Receives a `frameInfo` object with the following properties:
-
- `timestamp`: The system time (in milliseconds) when the last frame was rendered.
-
- `timeSincePreviousFrame`: Time (in milliseconds) since the previous frame. This is `null` for the first frame after activation and approximately 16 ms on a 60 Hz display or 8 ms on a 120 Hz display, assuming no frames are dropped.
-
- `timeSinceFirstFrame`: The time (in milliseconds) elapsed since the callback was activated.
-
-
##### `autostart` (Optional)
-
-
- Determines if the callback should start automatically. Defaults to `true`.
-
-
#### Returns
-
-
The `useFrameCallback` hook returns an object with these properties:
-
-
- `setActive`: A function to start or stop the frame callback.
-
- `isActive`: A boolean indicating whether the callback is currently running.
-
- `callbackId`: A unique identifier for the frame callback.
+
- `.duration(durationMs: number)` sets the animation length in milliseconds, defaulting to `500`.
+
- `.delay(durationMs: number)` specifies a delay before starting the animation, defaulting to `0`.
+
- `.reduceMotion(reduceMotion: ReduceMotion)` adjusts the animation based on the device's reduced motion setting.
+
- `.withCallback(callback: (finished: boolean) => void)` triggers after the animation ends, indicating if it finished without interruptions.
### Remarks
-
- The function provided in the `callback` argument is automatically workletized and executed on the UI thread.
+
- Providing keyframe `0` or `from` is mandatory as it defines the initial state of the object to be animated.
+
- Ensure all style properties intended for animation have an initial value in other keyframes.
+
- Easing should only be applied to subsequent keyframes, not to keyframe `0`.
+
- Avoid using both `0` and `from`, or `100` and `to`, as it causes parsing conflicts.
+
- When animating transform styles, maintain the order of properties consistently across all keyframes.
### Platform Compatibility
···
|-|-|-|
|✅|✅|✅|
-
- Reference
-
- Arguments
-
- Returns
-
- Example
-
- Remarks
-
- Platform compatibility
+
## Your First Animation
+
+
This section introduces you to the basics of Reanimated. If you're new to this library, you'll find guidance on creating a simple animation that lays the foundation for more advanced skills.
-
## Reduced Motion Configuration
+
### Using an Animated Component
-
The `ReducedMotionConfig` component allows you to modify behavior based on the device's reduced motion accessibility setting. By default, it disables all animations when reduced motion is enabled on a device. You can customize this for your specific needs. For more information, refer to Accessibility and `useReducedMotion` in Reanimated.
+
To start animating components in React Native using Reanimated, import the `Animated` object:
```typescript
-
interface ReducedMotionConfig {
-
// Define properties or methods as needed
-
}
+
import Animated from "react-native-reanimated"
```
-
This component helps ensure that your application respects user preferences regarding motion settings.
-
-
## Glossary of Terms
-
-
### Animated Component
-
-
Animated components are those that can be animated using Reanimated. The library includes built-in components such as `Animated.View`, `Animated.Text`, and `Animated.ScrollView`.
+
The `Animated` object wraps native components like `View`, `ScrollView`, or `FlatList`. Use these components as you would any other JSX component:
```typescript
import Animated from 'react-native-reanimated';
-
function App() {
+
export default function App() {
return (
<Animated.View
style={{
···
```
-
For components not included in Reanimated, you can make their props and styles animatable by wrapping them with `createAnimatedComponent`:
+
### Defining a Shared Value
-
```typescript
-
import Animated from "react-native-reanimated"
-
import { Circle } from "react-native-svg"
-
-
const AnimatedCircle = Animated.createAnimatedComponent(Circle)
-
```
-
-
### Shared Value
-
-
Shared values are essential for animations in Reanimated. They are defined using the `useSharedValue` hook and accessed or modified via their `.value` property.
+
Shared values are essential for animations, acting like React state synchronized between JavaScript and the native side. Create shared values using `useSharedValue`:
```typescript
import { useSharedValue } from "react-native-reanimated"
-
-
function App() {
-
const sv = useSharedValue(0)
-
-
const handlePress = () => {
-
sv.value += 10
-
}
-
-
// rest of your glamorous code ✨
-
}
```
-
Shared values can store any type and automatically synchronize data between the JavaScript thread and the UI thread.
-
-
### Animatable Value
-
-
An animatable value is a type that can be used for animations, including numbers, strings, and arrays of numbers. Strings in specific formats like `"10deg"`, `"21%"`, or colors such as `"#ffaabb"` or `"rgba(100, 200, 100, 0.7)"` are also animatable.
-
-
### Animation Function
-
-
Animation functions define how animations should behave. Reanimated provides three built-in animation functions:
-
-
- `withSpring`: Creates spring-based animations.
-
- `withTiming`: Creates duration and easing-based animations.
-
- `withDecay`: Mimics motion with a given deceleration rate.
-
-
These can be combined with modifiers for complex animations.
-
-
### Animation Modifier
-
-
Animation modifiers customize animations. Known as higher-order animations, Reanimated includes:
-
-
- `withDelay`: Adds a delay before the animation starts.
-
- `withRepeat`: Repeats an animation a specified number of times.
-
- `withSequence`: Chains animations sequentially.
-
- `withClamp`: Limits animation boundaries to a specific range.
-
-
### Animation Object
-
-
An animation object is returned from animation functions and modifiers, containing the current state of the animation. It includes start and end conditions and an `onFrame` function for calculating each frame's state.
-
-
When passed to a shared value, it is treated as an animatable value:
-
-
```typescript
-
sv.value = withSpring(100)
-
```
-
-
### Animations in Inline Styling
-
-
Shared values can be directly used in the `style` property without `useAnimatedStyle`.
-
-
Example:
-
-
```typescript
-
function App() {
-
const width = useSharedValue(100);
-
-
return <Animated.View style={{ width }} />;
-
}
-
```
-
-
### Layout Animation Modifier
-
-
Layout animation modifiers customize layout animations. Example usage:
-
-
```typescript
-
<Animated.View entering={FadeOutLeft.duration(500).easing(Easing.ease)} />
-
```
-
-
Built-in modifiers include:
-
-
- `.duration(durationMs: number)`: Sets the animation length in milliseconds.
-
- `.easing(easingFunction: EasingFunction)`: Defines the animation curve.
-
- `.springify()`: Enables spring-based animations.
-
- `.damping(value: number)`: Controls how quickly a spring stops moving.
-
- `.withCallback(callback: (finished: boolean) => void)`: Triggers after the animation ends.
-
-
### Worklet
-
-
Worklets are short-running JavaScript functions executed on the UI thread. They can also run on the JavaScript thread like regular functions.
-
-
Code is often automatically workletized and runs on the UI thread by default:
-
-
```typescript
-
const style = useAnimatedStyle(() => {
-
console.log("Running on the UI thread")
-
return { opacity: 0.5 }
-
})
-
```
-
-
Custom worklets can be created using the `"worklet";` directive:
-
-
```typescript
-
function myWorklet() {
-
"worklet"
-
console.log("Running on the UI thread")
-
}
-
```
-
-
Use `runOnUI` to manually execute worklets on the UI thread:
-
-
```typescript
-
function myWorklet(greeting) {
-
"worklet"
-
console.log(`${greeting} from the UI thread`)
-
}
-
-
function onPress() {
-
runOnUI(myWorklet)("Howdy")
-
}
-
```
-
-
### To Workletize
-
-
Converts a JavaScript function into an object that can be serialized and executed on the UI thread. Functions marked with `"worklet";` are automatically workletized by the Reanimated Babel plugin.
-
-
### JavaScript Thread
-
-
The JavaScript thread handles code execution in the app, serving as the primary location for React Native app code execution.
-
-
### UI Thread
-
-
The UI thread manages user interface updates and is also known as the Main thread. More information can be found in the Threading model article of the official React Native documentation.
-
-
### Reanimated Babel Plugin
-
-
This plugin automatically workletizes certain functions used with Reanimated, reducing boilerplate code. Details are available in the Reanimated Babel plugin README.
-
-
## withDelay
+
Define shared values within your component's body to store any JS value or data structure.
-
`withDelay` is an animation modifier that allows you to initiate an animation after a specified delay period.
-
-
### Reference
+
For example, set a default value of `100` for width in an `Animated.View`:
```typescript
-
import { withDelay } from "react-native-reanimated"
-
-
function App() {
-
sv.value = withDelay(500, withTiming(0))
-
// ...
-
}
-
```
-
-
#### Arguments
-
-
- **`delayMs`**: Specifies the duration (in milliseconds) before the animation begins.
-
-
- **`delayedAnimation`**: The animation that will be delayed.
-
-
- **`reduceMotion`** *(Optional)*: Determines how the animation responds to the device's reduced motion accessibility setting.
-
-
#### Returns
-
-
The `withDelay` function returns an animation object representing the current state of the animation. This object can either be directly assigned to a shared value or used as a value for a style object returned from `useAnimatedStyle`.
-
-
### Example
-
-
*(Example content would go here)*
-
-
### Platform Compatibility
-
-
|Android|iOS|Web|
-
|-|-|-|
-
|✅|✅|✅|
-
-
***
-
-
## useAnimatedKeyboard in React Native Reanimated (Version: 3.x)
-
-
### Overview
-
-
The `useAnimatedKeyboard` hook allows developers to create animations that respond to the state and height of the virtual keyboard.
-
-
> **Caution:**\
-
> The Android implementation of `useAnimatedKeyboard` has limitations on devices running Android SDK versions below 30. For more details, refer to the remarks section.
-
-
### Reference
-
-
```typescript
-
import { useAnimatedKeyboard, useAnimatedStyle } from "react-native-reanimated"
+
import Animated, { useSharedValue } from 'react-native-reanimated';
export default function App() {
-
const keyboard = useAnimatedKeyboard()
-
-
const animatedStyles = useAnimatedStyle(() => ({
-
transform: [{ translateY: -keyboard.height.value }],
-
}))
-
}
-
```
-
-
#### Arguments
-
-
##### `options` (Optional)
-
-
An optional configuration object that includes:
-
-
- **isStatusBarTranslucentAndroid**:\
-
Removes the top inset on Android when set to `true`, allowing for a translucent status bar. Defaults to `false`. This option is ignored on iOS.
-
-
#### Returns
-
-
The `useAnimatedKeyboard` hook returns an object with the following fields:
-
-
|Name|Type|Description|
-
|-|-|-|
-
|height|`SharedValue<number>`|A shared value representing the current height of the keyboard.|
-
|state|`SharedValue<KeyboardState>`|A shared value indicating the current state of the keyboard. Possible states: `{ CLOSED, OPEN, CLOSING, OPENING }`|
-
-
### Remarks
-
-
- **Android Specifics**:\
-
Ensure that `android:windowSoftInputMode` is set to `adjustResize` in your `AndroidManifest.xml`. This setting disables the default Android behavior (resizing the view for keyboard accommodation) across the app. By using values from the `useAnimatedKeyboard` hook, you can manage the keyboard manually. Unmounting all components that use this hook will revert to the default Android behavior.
-
-
- **Root View Management**:\
-
On Android, employing the `useAnimatedKeyboard` hook expands the root view to full screen (immersive mode) and manages insets:
-
-
- With `isStatusBarTranslucentAndroid` set to `false`, it applies a top margin based on the insets.
-
- When `true`, it sets the top margin to `0`.
-
- Similarly, with `isNavigationBarTranslucentAndroid`:
-
- `false`: Applies bottom margin according to the insets.
-
- `true`: Sets bottom margin to `0`.
-
-
- **Native Header Navigation**:\
-
On Android, using native header navigation means that `isStatusBarTranslucentAndroid` does not affect the top inset.
-
-
- **SDK Limitations**:\
-
For devices running Android SDK versions below 30, if the status bar is hidden, the keyboard reverts to default Android behavior.
-
-
### Platform Compatibility
-
-
|Android|iOS|Web|
-
|-|-|-|
-
|✅|✅|❌|
-
-
- **Reference**
-
-
- Arguments
-
- Returns
-
-
- **Example**
-
-
- **Remarks**
-
-
- **Platform Compatibility**
-
-
## useComposedEventHandler Hook
-
-
The `useComposedEventHandler` hook allows you to combine multiple event handlers, such as those created with `useAnimatedScrollHandler`, into a single handler.
-
-
### Reference Example
-
-
```typescript
-
import Animated, {
-
useAnimatedScrollHandler,
-
useComposedEventHandler,
-
} from 'react-native-reanimated';
-
-
function ComposedEventHandlerExample() {
-
const onScrollHandler1 = useAnimatedScrollHandler({
-
onScroll(e) {
-
console.log('Scroll handler 1 onScroll event');
-
},
-
});
-
-
const onScrollHandler2 = useAnimatedScrollHandler({
-
onScroll(e) {
-
console.log('Scroll handler 2 onScroll event');
-
},
-
});
-
-
const composedHandler = useComposedEventHandler([
-
onScrollHandler1,
-
onScrollHandler2,
-
]);
+
const width = useSharedValue(100);
return (
-
<View style={styles.container}>
-
<Animated.ScrollView style={styles.scroll} onScroll={composedHandler}>
-
<Content />
-
</Animated.ScrollView>
-
</View>
+
<Animated.View
+
style={{
+
width,
+
height: 100,
+
backgroundColor: 'violet',
+
}}
+
/>
);
```
-
#### Arguments
-
-
- **`handlers`**: An array of event handlers created using the `useEvent` hook. The `useComposedEventHandler` hook updates whenever there are changes in these handlers.
-
-
#### Returns
-
-
The hook returns a handler object that can be used with any `Animated component`. This handler should be assigned to the corresponding `onEvent` prop (e.g., `onScroll` for scroll-related handlers). For better code clarity, it's recommended to use multiple composed handlers if your aggregated handler manages various events.
-
-
### Remarks
-
-
- The returned handler combines the functionalities of all provided handlers. This allows multiple handlers to respond to a single event and manage different types of events with one object.
-
- It functions effectively when used with multiple `Animated components`, triggering event callbacks for each connected component.
-
-
### Platform Compatibility
-
-
|Android|iOS|Web|
-
|-|-|-|
-
|✅|✅|✅|
-
-
## dispatchCommand
-
-
The `dispatchCommand` function enables the execution of commands directly on a native component from the UI thread.
-
-
### Reference
-
-
```typescript
-
import { dispatchCommand } from 'react-native-reanimated';
-
-
function App() {
-
const animatedRef = useAnimatedRef();
-
-
const gesture = Gesture.Tap().onStart(() => {
-
dispatchCommand(animatedRef, 'focus');
-
});
-
-
return (
-
<>
-
<AnimatedTextInput ref={animatedRef} style={styles.input} />
-
<GestureDetector gesture={gesture}>
-
<Button title="Focus" />
-
</GestureDetector>
-
</>
-
);
-
}
-
```
-
-
#### Arguments
-
-
- **`animatedRef`**: An animated reference linked to the component you wish to update. This reference must be associated with either an Animated component or a React Native built-in component.
-
-
- **`commandName`**: The name of the command to execute, such as `'focus'` or `'scrollToEnd'`.
-
-
- **`args` (Optional)**: An array of arguments for the command. Defaults to an empty array if not provided.
-
-
### Example
-
-
```typescript
-
const goDown = Gesture.Tap().onStart(() => {
-
dispatchCommand(tosRef, "scrollToEnd", [true])
-
dispatchCommand(loginRef, "focus")
-
})
-
```
-
-
### Remarks
-
-
- Commands vary depending on the component. Refer to the relevant React Native documentation for available commands specific to each component.
-
-
### Platform Compatibility
-
-
|Android|iOS|Web|
-
|-|-|-|
-
|✅|✅|❌|
-
-
## withClamp
-
-
`withClamp` is an animation modifier that restricts the movement of your animation within a specified range. It's typically used in conjunction with `withSpring`.
-
-
### Reference
-
-
```typescript
-
import { withClamp } from "react-native-reanimated"
-
-
function App() {
-
sv.value = withClamp({ min: -1, max: 1 }, withSpring(0))
-
// ...
-
}
-
```
-
-
#### Arguments
-
-
##### `config`
-
-
An object containing the following properties:
-
-
|Name|Type|Description|
-
|-|-|-|
-
|min|number|Optional. The lowest value your animation can reach.|
-
|max|number|Optional. The highest value your animation can reach.|
-
-
##### `animation`
-
-
The spring animation you wish to clamp.
-
-
```typescript
-
const clampedStyleWithDelay = useAnimatedStyle(() => {
-
return {
-
width: withClamp({ min: 0, max: 100 }, withSpring(randomWidth.value)),
-
}
-
})
-
```
-
-
#### Returns
-
-
`withClamp` returns an animation object. This can be directly assigned to a shared value or used as a style value in `useAnimatedStyle`.
-
-
|Platform|Supported|
-
|-|-|
-
|Android|✅|
-
|iOS|✅|
-
|Web|✅|
-
-
## useAnimatedSensor
-
-
`useAnimatedSensor` allows you to create animations based on device sensor data. It provides access to:
-
-
- **Accelerometer**: Measures device acceleration (excluding gravity) along the x, y, and z axes.
-
- **Gyroscope**: Captures the rotation rate of the device along the x, y, and z axes.
-
- **Gravity**: Provides the current gravity vector along the x, y, and z axes.
-
- **Magnetic Field**: Measures the Earth's magnetic field strength and direction in microtesla (μT).
-
- **Rotation**: Represents the device orientation using Euler angles and a quaternion.
-
-
For comprehensive documentation, refer to the Sensors guide on Android Developers and Device Motion in Apple Developer documentation.
-
-
### Reference
-
-
```typescript
-
import { useAnimatedSensor, SensorType } from "react-native-reanimated"
-
-
function App() {
-
const gyroscope = useAnimatedSensor(SensorType.GYROSCOPE)
-
-
useDerivedValue(() => {
-
const { x, y, z } = gyroscope.sensor.value
-
})
-
}
-
```
-
-
#### Arguments
-
-
##### `sensorType`
-
-
Specifies the sensor type using a `SensorType` enum:
-
-
- `ACCELEROMETER`: Measures device acceleration in m/s².
-
- `GYROSCOPE`: Captures rotation rate in radians per second.
-
- `GRAVITY`: Provides gravity vector in m/s².
-
- `MAGNETIC_FIELD`: Measures magnetic field strength in microtesla (μT).
-
- `ROTATION`: Represents orientation using Euler angles and a quaternion.
-
-
##### `config` (Optional)
-
-
|Name|Type|Default|Description|
-
|-|-|-|-|
-
|interval|`number \| "auto"`|`"auto"`|Time between sensor readings in milliseconds. `"auto"` matches the device's screen refresh rate.|
-
|adjustToInterfaceOrientation|`boolean`|`true`|Adjusts measurements to the current interface orientation.|
-
|iosReferenceFrame|`IOSReferenceFrame`|`IOSReferenceFrame.Auto`|Frame of reference for iOS sensors.|
-
-
Available `IOSReferenceFrame` options:
-
-
- `xArbitraryZVertical`: Z axis is vertical, X axis arbitrary in horizontal plane.
-
- `xArbitraryCorrectedZVertical`: Improved rotation accuracy with Z vertical and X arbitrary.
-
- `XMagneticNorthZVertical`: Z axis vertical, X points to magnetic north.
-
- `XTrueNorthZVertical`: Z axis vertical, X points to geographic north.
-
- `Auto`: Defaults based on device capabilities.
-
-
#### Returns
-
-
`useAnimatedSensor` returns an object:
-
-
|Name|Type|Description|
-
|-|-|-|
-
|sensor|`SharedValue<Value3D \| ValueRotation>`|Shared value with sensor measurements.|
-
|unregister|`() => void`|Stops listening to sensor updates when called.|
-
|isAvailable|`boolean`|Indicates if the sensor is available for use.|
-
|config|`SensorConfig`|Contains sensor configuration details.|
-
-
The shared value from the **rotation sensor** includes:
-
-
- Euler angles: `roll`, `pitch`, `yaw`.
-
- Quaternion components: `qw`, `qx`, `qy`, `qz`.
-
- Interface orientation.
-
-
Other sensors return measurements on x, y, z axes and interface orientation.
-
-
`InterfaceOrientation` enum values:
-
-
- `ROTATION_0`: Default rotation on Android, portrait on iOS.
-
- `ROTATION_90`: 90 degrees on Android, landscape right on iOS.
-
- `ROTATION_180`: 180 degrees on Android, upside down on iOS.
-
- `ROTATION_270`: 270 degrees on Android, landscape left on iOS.
-
-
### Example
-
-
```typescript
-
export default function App() {
-
const gravity = useAnimatedSensor(SensorType.GRAVITY);
-
-
const animatedStyle = useAnimatedStyle(() => {
-
return {
-
transform: [
-
{ translateX: withSpring(gravity.sensor.value.x * 20) },
-
{ translateY: withSpring(gravity.sensor.value.y * 20) },
-
],
-
};
-
});
-
-
return (
-
<View style={styles.container}>
-
<Animated.View style={[styles.box, animatedStyle]} />
-
</View>
-
);
-
}
-
```
-
-
### Remarks
-
-
- On iOS, enable location services (`Settings > Privacy > Location Services`) to read sensor data.
-
- On Web, ensure the device supports sensors and the application is served over HTTPS.
-
- Most sensors operate at resolutions up to 100Hz.
-
- Sensor data can be accessed on both UI and JavaScript threads.
-
-
### Platform Compatibility
-
-
|Android|iOS|Web|
-
|-|-|-|
-
|✅|✅|✅|
-
-
## setNativeProps
-
-
The `setNativeProps` function allows for the imperative updating of component properties in React Native. It serves as an escape hatch intended for specific edge cases.
-
-
> **Caution:**\
-
> Prefer using `useAnimatedStyle` and `useAnimatedProps` when animating styles or properties, reserving `setNativeProps` for exceptional situations.
-
-
### Reference
-
-
```typescript
-
import { setNativeProps } from 'react-native-reanimated';
-
-
function App() {
-
const animatedRef = useAnimatedRef();
-
-
const tap = Gesture.Tap().onEnd(() => {
-
setNativeProps(animatedRef, { text: '' });
-
});
-
-
return <TextInput ref={animatedRef} />;
-
}
-
```
-
-
#### Arguments
-
-
- **`animatedRef`:**\
-
An animated reference linked to the component you wish to update. This animated reference must be passed either to an Animated component or a React Native built-in component.
-
-
- **`updates`:**\
-
An object containing properties that need updating, which can include both style properties (e.g., `width`, `backgroundColor`) and regular properties (e.g., `text`).
-
-
#### Returns
-
-
The function returns `undefined`.
-
-
### Remarks
-
-
- Prioritize using `useAnimatedStyle` and `useAnimatedProps` for animating styles or properties.
-
- Ensure that `setNativeProps` is used exclusively on the UI thread.
-
- The `setNativeProps` function was designed to facilitate the imperative updating of props from gesture handlers. In other scenarios, it may require an additional `runOnUI` call, making React Native's built-in `setNativeProps` more efficient with fewer runtime transitions.
-
-
### Platform Compatibility
-
-
|Android|iOS|Web|
-
|-|-|-|
-
|✅|✅|✅|
-
-
***
-
-
## React Native Reanimated: useReducedMotion Hook (Version 3.x)
-
-
### Overview
-
-
The `useReducedMotion` hook in React Native Reanimated allows developers to check the system's reduced motion setting. This is particularly useful for disabling animations when users prefer less motion.
-
-
### Reference
-
-
```typescript
-
import { useReducedMotion } from "react-native-reanimated"
-
-
function App() {
-
const reduceMotion = useReducedMotion()
-
-
if (reduceMotion) {
-
// Display static content ✨
-
} else {
-
// Run animations ✨
-
}
-
-
// Additional logic...
-
}
-
```
-
-
#### Returns
-
-
The `useReducedMotion` hook returns a boolean value indicating whether the reduced motion setting was enabled at the start of the app.
-
-
### Example Usage
-
-
```typescript
-
import { useReducedMotion } from 'react-native-reanimated';
-
-
function App() {
-
const reduceMotion = useReducedMotion();
-
-
if (reduceMotion) {
-
return <StaticContent />;
-
} else {
-
return <AnimatedContent />;
-
}
-
}
-
```
-
-
### Remarks
-
-
- Changing the reduced motion setting does not trigger a component rerender.
-
- Unlike `AccessibilityInfo.isReduceMotionEnabled()`, `useReducedMotion` provides the value synchronously.
-
-
### Platform Compatibility
-
-
|Android|iOS|Web|
-
|-|-|-|
-
|✅|✅|✅|
-
-
This hook is compatible across Android, iOS, and Web platforms.
-
-
## makeMutable
-
-
**Caution:** The use of `makeMutable` is generally discouraged. It's recommended to opt for the `useSharedValue` hook unless you are fully aware of its implications (refer to the Remarks section).
-
-
Internally, `makeMutable` is utilized by the `useSharedValue` hook to generate a shared value. This function allows the creation of mutable values without relying on the hook, which can be beneficial in specific scenarios such as within the global scope or when managing an array of mutable values.
-
-
The object produced by `makeMutable` mirrors that returned by the `useSharedValue` hook, ensuring consistent usage thereafter.
-
-
### Reference
-
-
```typescript
-
import { makeMutable } from "react-native-reanimated"
-
-
const mv = makeMutable(100)
-
```
-
-
#### Arguments
-
-
##### `initial`
-
-
This argument specifies the initial value to be stored in the mutable. It can encompass any JavaScript data type such as `number`, `string`, or `boolean`, and also includes complex structures like arrays and objects.
-
-
#### Returns
-
-
`makeMutable` yields a mutable value initialized with the provided `initial`. Access to the stored data is possible through its `value` property or via `get` and `set` methods.
-
-
### Example
-
-
### Remarks
-
-
**Info:** The term *mutable value* refers to an object created by `makeMutable`, distinguishing it from a *shared value*, which is essentially a mutable value with automatic cleanup.
-
-
- All remarks applicable to the `useSharedValue` hook are relevant to `makeMutable`.
-
- Avoid invoking `makeMutable` directly within component scope. Component re-renders will generate a new object, potentially resetting the initial value and losing previous state.
-
-
```typescript
-
function App() {
-
const [counter, setCounter] = useState(0)
-
const mv = makeMutable(counter) // 🚨 creates a new mutable value on each render
-
-
useEffect(() => {
-
const interval = setInterval(() => {
-
setCounter((prev) => prev + 1) // updates the counter stored in component state
-
}, 1000)
-
-
return () => {
-
clearInterval(interval)
-
}
-
}, [mv])
-
-
useAnimatedReaction(
-
() => mv.value,
-
(value) => {
-
console.log(value) // prints 0, 1, 2, ...
-
}
-
)
-
}
-
```
-
-
- Utilize `cancelAnimation` to halt all ongoing animations on a mutable value if it becomes unnecessary and animations are still active. Exercise caution with infinite animations as they require manual cancellation.
-
-
```typescript
-
function App() {
-
const mv = useMemo(() => makeMutable(0), [])
-
-
useEffect(() => {
-
mv.value = withRepeat(withSpring(100), -1, true) // creates an infinite animation
-
-
return () => {
-
cancelAnimation(mv) // ✅ stops the infinite animation on component unmount
-
}
-
}, [])
-
}
-
```
-
-
- `cancelAnimation` is not needed for non-animated values as they are automatically garbage collected when no references remain.
-
-
```typescript
-
const someFlag = makeMutable(false)
-
-
function App() {
-
someFlag.value = true // ✅ no need to cancel the animation later on
-
}
-
```
-
-
- When opting for `makeMutable`, adhere to React's rules and avoid common pitfalls associated with `useRef`, such as modifying references during rendering (see the **Pitfall** section in the useRef documentation).
-
-
#### Comparison with `useSharedValue`
-
-
|Feature|`makeMutable`|`useSharedValue`|
-
|-|-|-|
-
|Object Creation|Creates a new object on each call|Reuses the same object on each call|
-
|Initial Value Change|A new object is created if `initial` changes|The initially created object remains unchanged if `initialValue` changes|
-
|Scope Usage|Can be used outside of component scope|Limited to use within component scope|
-
|Loop Usage|Usable in loops with variable iterations|Usable in loops only if the number of hooks (`useSharedValue` calls) is constant|
-
|Animation Cancellation|Does not automatically cancel animations on unmount|Automatically cancels animations when the component unmounts|
+
### Using a Shared Value
-
### Platform Compatibility
+
Create an animation that modifies the `width` of an element by `50px` on each button press. Modify the shared value connected to the `Animated.View`'s width property.
-
|Android|iOS|Web|
-
|-|-|-|
-
|✅|✅|✅|
-
-
## Accurate Call Stacks
-
-
When debugging Reanimated code, you might come across error or warning call stacks that do not clearly point to the root cause of an issue. These stacks can be misleading because they frequently emphasize code from Reanimated's internal workings instead of highlighting the misuse of the Reanimated API, which is often the actual source of the problem.
+
Access and modify values stored in shared values using their `.value` property:
```typescript
-
// Example TypeScript snippet for context (not part of original content)
-
function debugReanimatedCode() {
-
// Debugging logic here
-
}
-
```
-
-
|Aspect|Description|
-
|-|-|
-
|**Issue**|Misleading call stacks in error or warning messages.|
-
|**Cause**|Call stacks often highlight Reanimated's internal code rather than API misuse.|
-
|**Impact**|Difficulty in identifying the true source of problems during debugging.|
-
-
Understanding this behavior is crucial for effectively diagnosing and resolving issues within Reanimated projects.
-
-
## Animating Styles and Props
-
-
In this section, we explore different methods for passing animation styles to components. We will differentiate between animating styles and props using `useAnimatedStyle` and `useAnimatedProps`.
-
-
### Animating Styles
-
-
Previously, we learned about simple animations and shared values. While inline styling works well in basic cases, it has limitations, such as not allowing access to the value stored in a shared value for complex operations.
-
-
```typescript
+
import { Button, View } from 'react-native';
import Animated, { useSharedValue } from 'react-native-reanimated';
-
function App() {
+
export default function App() {
const width = useSharedValue(100);
-
return <Animated.View style={{ width }} />;
-
}
-
```
-
-
For example, multiplying a shared value before assigning it to the `style` prop is not possible:
-
-
```typescript
-
<Animated.View style={{ width: width * 5 }} /> // This won't work
-
```
-
-
Consider an example where a box moves right on button press:
-
-
```typescript
-
import { View, Button } from 'react-native';
-
import Animated, { useSharedValue, withSpring } from 'react-native-reanimated';
-
-
function App() {
-
const translateX = useSharedValue(0);
-
const handlePress = () => {
-
translateX.value = withSpring(translateX.value + 50);
+
width.value = width.value + 50;
};
return (
-
<View style={styles.container}>
-
<Animated.View style={[styles.box, { transform: [{ translateX }] }]} />
+
<View style={{ flex: 1, alignItems: 'center' }}>
+
<Animated.View
+
style={{
+
width,
+
height: 100,
+
backgroundColor: 'violet',
+
}}
+
/>
<Button onPress={handlePress} title="Click me" />
</View>
);
```
-
To customize shared value changes based on user input, `useAnimatedStyle` is used for more control and flexibility:
-
-
```typescript
-
export default function App() {
-
const translateX = useSharedValue<number>(0);
+
Avoid directly modifying shared values without using the `.value` property, as in `sv.value = sv.value + 100`.
-
const handlePress = () => {
-
translateX.value += 50;
-
};
+
### Using an Animation Function
-
const animatedStyles = useAnimatedStyle(() => ({
-
transform: [{ translateX: withSpring(translateX.value * 2) }],
-
}));
-
-
return (
-
<>
-
<Animated.View style={[styles.box, animatedStyles]} />
-
<View style={styles.container}>
-
<Button onPress={handlePress} title="Click me" />
-
</View>
-
</>
-
);
-
}
-
```
-
-
`useAnimatedStyle` allows access to the shared value's `.value`, enabling operations like multiplication before assigning it to `style`. It also centralizes animation logic.
-
-
### Animating Props
-
-
While many values are animated via the `style` property, sometimes props need animating. For example, SVG elements use props instead of styles:
+
To animate smoothly, import and use the `withSpring` function. Wrap it around the new width value to create a spring animation:
```typescript
-
<Circle cx="50" cy="50" r="10" fill="blue" />
-
```
-
-
To animate non-Reanimated components' props, wrap them with `createAnimatedComponent`:
-
-
```typescript
-
import Animated from "react-native-reanimated"
-
import { Circle } from "react-native-svg"
-
-
const AnimatedCircle = Animated.createAnimatedComponent(Circle)
-
```
-
-
Animating the radius of an SVG circle can be done by passing a shared value as a prop:
-
-
```typescript
-
import { useSharedValue } from 'react-native-reanimated';
-
import { Svg } from 'react-native-svg';
-
-
function App() {
-
const r = useSharedValue(10);
-
-
return (
-
<Svg>
-
<AnimatedCircle cx="50" cy="50" r={r} fill="blue" />
-
</Svg>
-
);
-
}
-
```
-
-
For encapsulating animation logic and accessing `.value`, `useAnimatedProps` is used:
-
-
```typescript
-
const AnimatedCircle = Animated.createAnimatedComponent(Circle);
+
import { Button, View } from 'react-native';
+
import Animated, { useSharedValue, withSpring } from 'react-native-reanimated';
export default function App() {
-
const r = useSharedValue<number>(20);
+
const width = useSharedValue(100);
const handlePress = () => {
-
r.value += 10;
+
width.value = withSpring(width.value + 50);
};
-
const animatedProps = useAnimatedProps(() => ({
-
r: withTiming(r.value),
-
}));
-
return (
-
<View style={styles.container}>
-
<Svg style={styles.svg}>
-
<AnimatedCircle
-
cx="50%"
-
cy="50%"
-
fill="#b58df1"
-
animatedProps={animatedProps}
-
/>
-
</Svg>
+
<View style={{ flex: 1, alignItems: 'center' }}>
+
<Animated.View
+
style={{
+
width,
+
height: 100,
+
backgroundColor: 'violet',
+
}}
+
/>
<Button onPress={handlePress} title="Click me" />
</View>
);
```
-
In `useAnimatedProps`, return an object with animatable props, then pass it to the `animatedProps` prop of an Animated component.
+
This creates a bouncy spring animation for the element's width.
### Summary
-
- Inline styles are simple but limited for complex animations.
-
- Props differ from styles as they aren't passed via the `style` object.
-
- `useAnimatedStyle` and `useAnimatedProps` provide access to shared values' `.value`, enhancing animation control.
-
- Custom animatable components can be created with `Animated.createAnimatedComponent`.
-
-
### What's Next?
-
-
In the next section, we'll delve into animation functions and customizing their behavior.
-
-
## React Native Reanimated: ReducedMotionConfig
-
-
**Version:** 3.x
-
-
### Overview
-
-
The `ReducedMotionConfig` component allows you to modify the behavior of animations based on a device's reduced motion accessibility setting. By default, it disables all animations when this setting is enabled. You can customize this behavior according to your specific needs. For more information about Accessibility and `useReducedMotion`, refer to Reanimated documentation.
-
-
> **Caution:** The new configuration will be applied globally across the entire application.
-
-
### Reference
-
-
```typescript
-
import { ReducedMotionConfig, ReduceMotion } from 'react-native-reanimated';
-
-
function App() {
-
return (
-
// ...
-
<ReducedMotionConfig mode={ReduceMotion.Never} />
-
// ...
-
);
-
}
-
```
-
-
#### Arguments
-
-
##### `mode`
-
-
This parameter determines how animations should respond to the device's reduced motion accessibility setting:
-
-
- **`ReduceMotion.System`:** Adjusts animation behavior based on the device's reduced motion setting. Animations are disabled when this setting is enabled; otherwise, they remain active.
-
-
- **`ReduceMotion.Always`:** Consistently disables animations, regardless of the device's accessibility configuration.
-
-
- **`ReduceMotion.Never`:** Ensures that animations remain enabled at all times.
-
-
### Platform Compatibility
-
-
|Android|iOS|Web|
-
|-|-|-|
-
|✅|✅|✅|
-
-
- Reference
-
- Arguments
-
- Example
-
- Platform compatibility
-
-
## Accurate Call Stacks
-
-
When debugging Reanimated code, developers might encounter misleading call stacks in errors or warnings. These stacks often highlight internal Reanimated code rather than pinpointing the misuse of the Reanimated API that caused the issue.
-
-
To improve this situation, Reanimated offers a Metro configuration wrapper named `wrapWithReanimatedMetroConfig`. This tool adjusts your Metro config to enhance the accuracy of call stacks for warnings and errors generated by the Reanimated library.
-
-
### Reference
-
-
For more precise call stacks, import `wrapWithReanimatedMetroConfig` from `react-native-reanimated/metro-config` and use it to wrap your existing Metro configuration in the `metro.config.js` file.
-
-
```typescript
-
// metro.config.js
-
import { wrapWithReanimatedMetroConfig } from "react-native-reanimated/metro-config"
-
-
const config = {
-
// Your existing Metro configuration options
-
}
-
-
export default wrapWithReanimatedMetroConfig(config)
-
```
-
-
### Example
-
-
The example below illustrates the difference in call stacks before and after applying the Reanimated Metro config wrapper. The **Before** scenario shows Reanimated source code as the error origin, while the **After** scenario reveals the actual incorrect code that caused the error.
-
-
|Before|After|
-
|-|-|
-
|||
-
-
### Remarks
-
-
- `wrapWithReanimatedMetroConfig` does not remove any stack frames; it only collapses irrelevant ones from Reanimated. To inspect these, you can expand collapsed stack frames by clicking on the **See N more frames** text at the bottom of the **Call Stack**.
-
-
|Collapsed|Expanded|
-
|-|-|
-
|||
-
-
- Some errors, especially those arising from asynchronous code, may still point to Reanimated internals instead of the exact problematic line in your code. This happens because stack traces can lose track of the original code that initiated the asynchronous operation. In such cases, manual debugging based on the error message is necessary to identify the potential cause of the problem.
-
-
## Logger Configuration for Reanimated
-
-
Reanimated provides warnings to highlight potential misuses of its API, such as altering shared values during component re-renders. These logs can be adjusted in verbosity.
-
-
By default, the logger configuration requires no setup and displays all warnings and errors. To customize this behavior, use the `configureReanimatedLogger` function.
-
-
### Reference
-
-
To alter the default Reanimated logger settings, import `configureReanimatedLogger` from `react-native-reanimated` and invoke it with your desired configuration:
-
-
```typescript
-
import {
-
configureReanimatedLogger,
-
ReanimatedLogLevel,
-
} from "react-native-reanimated"
-
-
// Default configuration example
-
configureReanimatedLogger({
-
level: ReanimatedLogLevel.warn,
-
strict: true, // Strict mode is enabled by default
-
})
-
```
-
-
#### Configuration Options
-
-
- **`level`:** Specifies the minimum log level to display using a value from `ReanimatedLogLevel`.
-
-
- **`strict`:** A boolean that toggles strict mode. Enabling it results in additional warnings to help identify potential code issues.
-
-
### Remarks
-
-
- The logger configuration is global, affecting all Reanimated warnings and errors. It cannot be configured on a per-file or per-component basis.
-
-
- Call `configureReanimatedLogger` before creating any Reanimated animations, typically in the root file of your application.
-
-
- This function is intended for app developers. Library creators using Reanimated should avoid including this call in their source code to prevent overriding users' configurations with the default settings.
-
-
### Platform Compatibility
-
-
|Android|iOS|Web|
-
|-|-|-|
-
|✅|✅|✅|
-
-
```markdown
-
# Guides
-
-
## Worklets
-
-
Worklets are brief JavaScript functions executed on the UI thread. Reanimated utilizes worklets to compute view styles and respond to events directly on the UI thread.
-
-
## Accessibility
-
-
This section delves into how Reanimated enhances accessibility in animations, particularly through its reduced motion feature. This functionality ensures a more comfortable experience for users with motion sensitivities or those who prefer minimal movement.
-
-
## Building for Android on Windows
-
-
This article outlines basic troubleshooting steps for issues encountered when building React Native apps with Reanimated for Android devices from a Windows host machine.
-
-
## Compatibility
-
-
Currently supported React Native versions (Paper)
-
-
## Contributing
-
-
Thank you for your interest in contributing to Reanimated! Contributions, whether through triaging and commenting on issues, extending documentation, or reviewing and submitting Pull Requests, are greatly appreciated.
-
-
## Debugging Worklets
-
-
Due to Reanimated's unique architecture and its use of a secondary JS runtime, debugging worklets can be challenging.
-
-
## Migration from 1.x
-
-
We aimed to facilitate incremental migration from Reanimated 1 to Reanimated 2.
-
-
## Migration from 2.x
-
-
Reanimated 3.x introduces no breaking changes in terms of API between versions 2.x and 3.x. All code written using the Reanimated v2 API will function in 3.x without modifications. However, Reanimated 3.x completely removes support for the Reanimated v1 API. For migration guidance from 1.x to 2.x, please refer to the Migration from 1.x to 2.x guide.
-
-
## Testing with Jest
-
-
Reanimated offers a testing API based on Jest, enabling users to mock web-based animations.
-
-
## Troubleshooting
-
-
Initialization issues
-
-
## Web Support
-
-
Reanimated can be launched in a web browser. In this context, all functionalities are implemented purely in JavaScript, which may result in reduced animation efficiency.
-
```
-
-
```markdown
-
# Core (Version: 3.x)
-
-
## useSharedValue
-
-
`useSharedValue` is used for defining shared values within your components. These shared values can be utilized across different parts of the component tree.
-
-
## useAnimatedStyle
-
-
With `useAnimatedStyle`, you can create a styles object akin to StyleSheet styles, which allows animation using shared values. This enables dynamic styling changes in response to animations.
-
-
## useAnimatedProps
-
-
`useAnimatedProps` facilitates the creation of an animated props object that can be animated with shared values. It is particularly useful for animating properties of third-party components by providing them with animated props.
-
-
## useAnimatedRef
-
-
The `useAnimatedRef` function provides a reference to a view, which can then be used in conjunction with functions like measure, scrollTo, and useScrollViewOffset to manipulate the view's position or dimensions.
-
-
## useDerivedValue
-
-
`useDerivedValue` allows for the creation of new shared values derived from existing ones. This ensures that these new values remain reactive and update automatically when their dependencies change.
-
-
## createAnimatedComponent
-
-
`createAnimatedComponent` enables you to transform any React Native component into an animated version. By wrapping a component with `createAnimatedComponent`, Reanimated can animate any prop or style associated with it, enhancing the component's interactivity.
-
-
## cancelAnimation
-
-
The `cancelAnimation` function is used to stop a running animation that is linked to a shared value. This allows for greater control over animations by providing the ability to halt them when necessary.
-
```
-
-
```markdown
-
# Version 3.x: Layout Animations Overview
-
-
## Entering/Exiting Animations
-
-
These animations are designed to animate elements as they enter into or exit from the view hierarchy, providing a dynamic user experience.
-
-
## Keyframe Animations
-
-
Keyframes offer a schema for defining complex animations. They provide greater flexibility compared to standard entering and exiting presets by allowing detailed control over animation sequences.
-
-
## Layout Transitions
-
-
Layout transitions enable smooth changes during layout updates, which may involve alterations in size or position. Both aspects can be animated to enhance visual fluidity.
-
-
## Custom Animations
-
-
Custom animations offer complete control over both entering/exiting animations and layout transitions. However, they are complex and challenging to maintain. It is advisable to start with predefined presets before opting for custom solutions.
-
-
## Skipping Layout Animations
-
-
The `LayoutAnimationConfig` component allows you to bypass entering and exiting animations when needed.
-
-
## List Layout Animations
-
-
With `itemLayoutAnimation`, you can specify a layout transition for list items during layout changes. Options include using predefined transitions like `LinearTransition` or creating custom ones.
-
```
-
-
## Worklets
-
-
Worklets are short-running JavaScript functions that execute on the UI thread, enabling efficient style calculations and event reactions. Reanimated leverages worklets for these tasks.
-
-
### Creating Worklets
-
-
To define a custom worklet, use the `'worklet';` directive at the start of your function:
-
-
```typescript
-
function myWorklet() {
-
"worklet"
-
console.log("Hello from a worklet")
-
}
-
```
-
-
The Reanimated Babel Plugin identifies functions marked with `'worklet'`, transforming them into serializable objects—a process known as workletization. These objects can then be executed on the UI thread.
-
-
### Automatic Workletization
-
-
When using Reanimated and Gesture Handler, code is typically automatically workletized and executed on the UI thread:
-
-
```typescript
-
import { useAnimatedStyle } from "react-native-reanimated"
-
-
function App() {
-
const style = useAnimatedStyle(() => {
-
// Executed on the UI thread
-
return { opacity: 0.5 }
-
})
-
}
-
```
-
-
### Manual Worklet Execution
-
-
To manually schedule worklet execution, use `runOnUI`:
-
-
```typescript
-
function myWorklet() {
-
"worklet"
-
console.log("Hello from the UI thread")
-
}
-
-
function onPress() {
-
runOnUI(myWorklet)()
-
}
-
```
-
-
Arguments can be passed to worklets as follows:
-
-
```typescript
-
function myWorklet(greeting: string) {
-
"worklet"
-
console.log(`${greeting} from the UI thread`)
-
}
-
-
function onPress() {
-
runOnUI(myWorklet)("Howdy")
-
}
-
```
-
-
### Worklet Closures
-
-
Worklets are closures, allowing them to access variables declared outside their scope. Only referenced variables are captured:
-
-
```typescript
-
const width = 135.5
-
-
function otherWorklet() {
-
"worklet"
-
console.log("Captured width is", width)
-
}
-
```
-
-
Avoid capturing large objects within worklets to prevent performance issues:
-
-
```typescript
-
const theme = {...}; // Large object
-
-
function myWorklet() {
-
'worklet';
-
console.log(theme.color); // 🚨 Captures entire `theme` object
-
}
-
```
-
-
To mitigate this, assign the needed property to a separate variable:
-
-
```typescript
-
const theme = {...};
-
const color = theme.color;
-
-
function myWorklet() {
-
'worklet';
-
console.log(color); // ✅ Captures only `color`
-
}
-
```
-
-
### Returning Data
-
-
Worklets can return data within the same thread:
-
-
```typescript
-
function returningWorklet() {
-
"worklet"
-
return "I'm back" // On the UI thread
-
}
-
-
function someWorklet() {
-
"worklet"
-
const what = returningWorklet() // Still on the UI thread
-
console.log("On the UI thread, other worklet says", what)
-
}
-
```
-
-
### Data Sharing Between Threads
-
-
Use shared values to pass data between the UI and JS threads:
-
-
```typescript
-
import { useSharedValue } from "react-native-reanimated"
-
-
function App() {
-
const width = useSharedValue(100)
-
-
function myWorklet() {
-
"worklet"
-
width.value += 50
-
}
-
-
useEffect(() => {
-
console.log(width.value) // Accessible on both JS and UI threads
-
}, [])
-
}
-
```
-
-
### Running Functions on the JS Thread
-
-
Use `runOnJS` to execute functions from the UI thread, often for non-worklet functions or React state updates:
-
-
```typescript
-
import { router } from "expo-router"
-
import { Gesture } from "react-native-gesture-handler"
-
-
function App() {
-
const tap = Gesture.Tap().onEnd(() => {
-
// Worklet context
-
runOnJS(router.back)()
-
})
-
}
-
```
-
-
Ensure functions passed to `runOnJS` are defined in the JavaScript thread scope:
-
-
```typescript
-
function App() {
-
const tap = Gesture.Tap().onEnd(() => {
-
// myFunction is defined on the UI thread 🚨
-
const myFunction = () => {}
-
runOnJS(myFunction)() // 💥 Error
-
})
-
}
-
```
-
-
### Custom Worklet Runtimes
-
-
Worklets can operate in custom runtimes beyond Reanimated's default. Libraries like VisionCamera and LiveMarkdown create their own worklet environments.
-
-
Create your own worklet runtime using `createWorkletRuntime`.
-
-
## Accessibility
-
-
This section discusses how Reanimated enhances accessibility in animations, particularly through its reduced motion functionality. This feature ensures a smoother experience for users with motion sensitivities or those who prefer less movement.
-
-
The reduced motion configuration allows you to define how animations should respond to the system's reduced motion setting. For any animation, the value can be set as follows:
-
-
- `ReduceMotion.System`: Adjusts the animation based on whether the device's reduced motion accessibility setting is activated. If enabled, the animation is disabled; otherwise, it remains active.
-
- `ReduceMotion.Always`: Consistently disables the animation, regardless of the device's accessibility configuration.
-
- `ReduceMotion.Never`: Ensures that the animation remains enabled at all times.
-
-
By default, all animations are configured with `ReduceMotion.System`.
-
-
### Reduced Motion in Animations
-
-
```typescript
-
import { withDelay, withTiming } from "react-native-reanimated"
-
-
function App() {
-
sv1.value = withTiming(0, { reduceMotion: ReduceMotion.System })
-
sv2.value = withDelay(
-
1000,
-
withTiming(toValue, { duration }),
-
ReduceMotion.System
-
)
-
// ...
-
}
-
```
-
-
When reduced motion is enabled:
-
-
- `withSpring` and `withTiming` return the `toValue` immediately.
-
- `withDecay` returns the current value immediately, considering the clamp parameter.
-
- `withDelay` initiates the next animation immediately.
-
- `withRepeat`:
-
- If `numberOfReps` is infinite or even and the animation is reversed, then the repeated animation does not start.
-
- Otherwise, the repeated animation runs once.
-
- `withSequence` exclusively starts animations that have reduced motion disabled.
-
-
Higher-order animations pass the configuration to their children only if the children haven't been configured by the user. For example:
-
-
This animation will instantaneously reach the `toValue`:
-
-
```typescript
-
import { withDelay, withTiming } from "react-native-reanimated"
-
-
function App() {
-
sv.value = withDelay(
-
1000,
-
withTiming(toValue, { duration }),
-
ReduceMotion.Always
-
)
-
// ...
-
}
-
```
-
-
This animation will execute as usual even if reduced motion is enabled on the device:
-
-
```typescript
-
import { withDelay, withTiming } from "react-native-reanimated"
-
-
function App() {
-
sv.value = withDelay(
-
1000,
-
withTiming(toValue, { duration }),
-
ReduceMotion.Never
-
)
-
// ...
-
}
-
```
-
-
And here `withTiming` will be executed as usual and without delay:
-
-
```typescript
-
import { withDelay, withTiming } from "react-native-reanimated"
-
-
function App() {
-
sv.value = withDelay(
-
1000,
-
withTiming(toValue, { duration, reduceMotion: ReduceMotion.Never }),
-
ReduceMotion.Always
-
)
-
// ...
-
}
-
```
-
-
### Reduced Motion in Layout Animations
-
-
```typescript
-
import { BounceIn } from "react-native-reanimated"
-
-
function App() {
-
const entering = BounceIn.reduceMotion(ReduceMotion.System)
-
// ...
-
}
-
```
-
-
When reduced motion is enabled:
-
-
- Entering, keyframe, and layout animations instantaneously reach their endpoints.
-
- Exiting animations and shared transitions are omitted.
-
-
### `useReducedMotion`
-
-
This hook returns a boolean indicating whether the reduced motion setting was enabled when the app started. It can be used in conjunction with other libraries or to conditionally display animations that are less intrusive.
-
-
```typescript
-
import { BounceIn } from "react-native-reanimated"
-
-
function App() {
-
const reduceMotion = useReducedMotion()
-
const entering = reduceMotion
-
? FadeIn.reduceMotion(ReduceMotion.Never)
-
: BounceIn
-
// ...
-
}
-
```
-
-
The provided content outlines a comprehensive guide for using various animations in React Native with the `react-native-reanimated` library. Below is a structured summary of the key points and features:
-
-
#### Overview
-
-
- **Library**: `react-native-reanimated`
-
- **Purpose**: To create smooth, performant animations on Android, iOS, and Web platforms.
-
- **Animations Covered**:
-
- Pinch
-
- Pinch Zoom
-
- Pinch Rotate
-
- Pinch Scale
-
- Pinch Translate
-
- Pinch X
-
- Pinch Y
-
- PinchXY
-
- PinchZoomRotate
-
- PinchZoomScale
-
- PinchZoomTranslate
-
- PinchZoomX
-
- PinchZoomY
-
- PinchZoomXY
-
- PinchZoomRotateScale
-
- PinchZoomRotateTranslate
-
- PinchZoomRotateX
-
- PinchZoomRotateY
-
- PinchZoomRotateXY
-
- PinchZoomScaleTranslate
-
- PinchZoomScaleX
-
- PinchZoomScaleY
-
- PinchZoomScaleXY
-
- PinchZoomTranslateX
-
- PinchZoomTranslateY
-
- PinchZoomTranslateXY
-
- PinchZoomRotateScaleTranslate
-
- PinchZoomRotateScaleX
-
- PinchZoomRotateScaleY
-
- PinchZoomRotateScaleXY
-
- PinchZoomRotateTranslateX
-
- PinchZoomRotateTranslateY
-
- PinchZoomRotateTranslateXY
-
- PinchZoomScaleTranslateX
-
- PinchZoomScaleTranslateY
-
- PinchZoomScaleTranslateXY
-
- PinchZoomRotateScaleTranslateX
-
- PinchZoomRotateScaleTranslateY
-
- PinchZoomRotateScaleTranslateXY
-
- Other animations like Bounce, Fade, Flip, etc.
-
-
#### Animation Configuration
-
-
##### Time-based Modifiers
-
-
- **Function**: `withTiming`
-
- **Customization**:
-
- `.easing(easingFunction: EasingFunction)`: Defines the animation curve. Default is `Easing.inOut(Easing.quad)`.
-
- Note: These modifiers do not affect spring animations.
-
-
##### Spring-based Modifiers
-
-
- **Function**: `withSpring`
-
- **Customization**:
-
- `.springify()`: Enables spring-based configuration.
-
- `.damping(value: number)`: Controls how quickly the spring stops. Default is `10`.
-
- `.mass(value: number)`: Represents the weight of the spring. Lower values make animations faster. Default is `1`.
-
- `.stiffness(value: number)`: Determines bounciness. Default is `100`.
-
- `.overshootClamping(value: boolean)`: Prevents bouncing over the target position. Default is `false`.
-
- `.restDisplacementThreshold(value: number)`: Displacement threshold for snapping to the final position without oscillations. Default is `0.001`.
-
- `.restSpeedThreshold(value: number)`: Speed threshold for snapping to the final position without oscillations. Default is `2`.
-
-
##### Common Modifiers
-
-
- **Customization**:
-
- `.duration(durationMs: number)`: Length of the animation in milliseconds. Default is `300`.
-
- `.delay(durationMs: number)`: Delay before starting the animation. Default is `0`.
-
- `.randomDelay()`: Randomizes delay between `0` and provided value, defaulting to `1000ms` if not specified.
-
- `.reduceMotion(reduceMotion: ReduceMotion)`: Adjusts animation based on device's reduced motion settings.
-
- `.withInitialValues(values: StyleProps)`: Overrides initial configuration of the animation.
-
- `.withCallback(callback: (finished: boolean) => void)`: Executes a callback after the animation ends, indicating if it finished without interruptions.
-
-
#### Platform Compatibility
-
-
- **Android**: Supported
-
- **iOS**: Supported
-
- **Web**: Supported
-
-
This guide provides developers with the tools to create and customize animations effectively across multiple platforms using `react-native-reanimated`.
-
-
## Troubleshooting React Native Reanimated Build Issues on Windows
-
-
This guide outlines basic troubleshooting steps for resolving issues encountered when building React Native apps with Reanimated for Android devices on a Windows host machine. Common errors include:
-
-
- `Execution failed for task ':react-native-reanimated:buildCMakeDebug[x86_64]'`
-
- `Execution failed for task ':react-native-reanimated:buildCMakeRelWithDebInfo[arm64-v8a]'`
-
- `Task :react-native-reanimated:buildCMakeDebug[x86_64] FAILED`
-
- `C/C++: ninja: error: mkdir(...): No such file or directory`
-
- `C++ build system [build] failed while executing`
-
- `Picked up _JAVA_OPTIONS`
-
-
### What Not to Do
-
-
If you encounter any of the above errors, avoid these actions:
-
-
#### ❌ Avoid Disabling New Architecture
-
-
Starting from React Native 0.76, New Architecture is enabled by default. Manually disabling it in `gradle.properties` does not resolve issues and merely delays them since legacy architecture will be phased out.
-
-
#### ❌ Avoid Downgrading Android Gradle Plugin (AGP)
-
-
Do not modify the AGP version in `gradle.properties`. Use the version specified in the official app template to prevent version conflicts and unsupported features.
-
-
#### ❌ Avoid Downgrading Reanimated or Other Dependencies
-
-
Downgrading increases technical debt. Newer versions of Reanimated include bug fixes and stability improvements. Always use the latest supported version, and consider upgrading all dependencies rather than downgrading them.
-
-
#### ❌ Avoid Posting Duplicate "Same Issue" Comments
-
-
Before reporting an error, search for similar issues on platforms like GitHub or Stack Overflow. Instead of posting duplicate comments, add a reaction to the original issue to indicate its impact.
-
-
### Recommended Actions
-
-
#### ✅ Ensure Correct Environment Setup
-
-
Follow all instructions in Set Up Your Environment. Run `npx react-native doctor` to identify any problems. Restart your terminal, IDE, or computer if changes have been made.
-
-
#### ✅ Use Compatible Reanimated Version
-
-
Use the latest supported version of Reanimated based on your app setup:
-
-
- **Expo SDK**: Match major and minor versions with Expo SDK.
-
- Example: Expo SDK 52 supports `~3.16.x`. Update to the latest patch, e.g., `3.16.7`.
-
-
|Expo SDK Version|Reanimated Version|
-
|-|-|
-
|`52`|`~3.16.1`|
-
|`51`|`~3.10.1`|
-
|`50`|`~3.6.2`|
-
-
- **Expo Prebuild or React Native without Framework**: Use a version compatible with your React Native version according to the Compatibility table.
-
-
#### ✅ Use Appropriate CMake Version
-
-
Ensure you use CMake `3.22.1` or newer. Customize the version using the `CMAKE_VERSION` environment variable, e.g., `set CMAKE_VERSION=3.31.1`. If unset, default is `3.22.1`.
-
-
#### ✅ Use Appropriate Ninja Version
-
-
Use Ninja `1.12.0` or newer (latest is `1.12.1`) as older versions may not handle long paths correctly.
-
-
#### ✅ Use Compatible Android NDK Version
-
-
Match the NDK version with that used in the official app template. It should be installed automatically during app build.
-
-
#### ✅ Unset `_JAVA_OPTIONS`
-
-
Unsetting this environment variable can resolve certain errors and allow builds to pass.
-
-
#### ✅ Enable Long Paths Support in Windows Registry
-
-
Follow instructions to enable long paths support on Windows.
-
-
#### ✅ Avoid Whitespace in Project Path
-
-
Paths with spaces may cause issues. Move projects to directories without whitespace, e.g., `D:\Mobile Apps\MyAwesomeProject`.
-
-
#### ✅ Ensure Short Project Path
-
-
Avoid paths longer than 240 characters. Move or clone the project to a shorter path, e.g., `D:\AwesomeProject`.
-
-
#### ✅ Remove or Invalidate Caches
-
-
Clear compilation artifacts in directories like:
-
-
- `android\build`
-
- `android\.cxx`
-
- `android\.gradle`
-
- `node_modules\react-native-reanimated\android\build`
-
-
Invalidate Android Studio caches (File → Invalidate Caches…).
-
-
#### ⚠️ Persistent Issues
-
-
If problems persist after following these steps, submit an issue in the repository with full build logs and a minimal reproducible example.
-
-
## Compatibility Table
-
-
### Currently Supported React Native Versions (Paper)
-
-
|Version|0.63|0.64|0.65|0.66|0.67|0.68|0.69|0.70|0.71|0.72|0.73|0.74|0.75|0.76|0.77|0.78|0.79|0.80|
-
|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|
-
|3.18.0|no|no|no|no|no|no|no|no|no|no|no|no|yes|yes|yes|yes|yes|yes|
-
|3.17.4 - 3.17.5|no|no|no|no|no|no|no|no|no|no|no|no|yes|yes|yes|yes|yes|no|
-
|3.17.1 – 3.17.3|no|no|no|no|no|no|no|no|no|no|no|no|yes|yes|yes|yes|no|no|
-
|3.17.0|no|no|no|no|no|no|no|no|no|no|no|no|yes|yes|yes|no|no|no|
-
|3.16.7|no|no|no|no|no|no|no|no|no|no|no|yes|yes|yes|yes|no|no|no|
-
|3.16.0 – 3.16.6|no|no|no|no|no|no|no|no|no|no|no|yes|yes|yes|no|no|no|no|
-
|3.15.x|no|no|no|no|no|no|no|no|no|no|no|yes|yes|no|no|no|no|no|
-
|3.9.x – 3.14.x|no|no|no|no|no|no|no|no|no|no|no|yes|no|no|no|no|no|no|
-
|3.6.x – 3.8.x|no|no|no|yes|yes|yes|yes|yes|yes|yes|yes|no|no|no|no|no|no|no|
-
|3.5.x|no|no|no|yes|yes|yes|yes|yes|yes|yes|no|no|no|no|no|no|no|no|
-
|3.3.x – 3.4.x|yes|yes|yes|yes|yes|yes|yes|yes|yes|yes|no|no|no|no|no|no|no|no|
-
|3.0.x – 3.2.x|yes|yes|yes|yes|yes|yes|yes|yes|yes|no|no|no|no|no|no|no|no|no|
-
|2.14.x – 2.17.x|yes|yes|yes|yes|yes|yes|yes|yes|yes|no|no|no|no|no|no|no|no|no|
-
|2.11.x – 2.13.x|yes|yes|yes|yes|yes|yes|yes|yes|no|no|no|no|no|no|no|no|no|no|
-
|2.10.x|yes|yes|yes|yes|yes|yes|yes|no|no|no|no|no|no|no|no|no|no|no|
-
|2.5.x – 2.9.x|yes|yes|yes|yes|yes|yes|no|no|no|no|no|no|no|no|no|no|no|no|
-
|2.3.x – 2.4.x|yes|yes|yes|yes|yes|no|no|no|no|no|no|no|no|no|no|no|no|no|
-
-
**Note:** Reanimated 2 will not receive support for the newest React Native versions. To access the latest features and updates, upgrade to Reanimated 3.
-
-
### Supported React Native Versions on the New Architecture (Fabric)
-
-
To use Reanimated with the experimental New Architecture, update the package to at least version 3.0.0. Due to numerous breaking changes related to the New Architecture in each React Native version, as a rule of thumb, Reanimated supports the latest stable version of React Native.
-
-
Reanimated supports bridgeless mode.
-
-
|Version|0.63|0.64|0.65|0.66|0.67|0.68|0.69|0.70|0.71|0.72|0.73|0.74|0.75|0.76|0.77|0.78|0.79|0.80|
-
|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|
-
|3.18.0|no|no|no|no|no|no|no|no|no|no|no|no|yes|yes|yes|yes|yes|yes|
-
|3.17.4 - 3.17.5|no|no|no|no|no|no|no|no|no|no|no|no|yes|yes|yes|yes|yes|no|
-
|3.17.1 – 3.17.3|no|no|no|no|no|no|no|no|no|no|no|no|yes|yes|yes|yes|no|no|
-
|3.17.0|no|no|no|no|no|no|no|no|no|no|no|no|yes|yes|yes|no|no|no|
-
|3.16.7|no|no|no|no|no|no|no|no|no|no|no|yes|yes|yes|yes|no|no|no|
-
|3.16.0 – 3.16.6|no|no|no|no|no|no|no|no|no|no|no|yes|yes|yes|no|no|no|no|
-
|3.15.x|no|no|no|no|no|no|no|no|no|no|no|yes|yes|no|no|no|no|no|
-
|3.9.x – 3.14.x|no|no|no|no|no|no|no|no|no|no|no|yes|no|no|no|no|no|no|
-
|3.6.x – 3.8.x|no|no|no|no|no|no|no|no|no|yes|yes|no|no|no|no|no|no|no|
-
|3.1.x – 3.5.x|no|no|no|no|no|no|no|no|no|yes|no|no|no|no|no|no|no|no|
-
|3.0.x|no|no|no|no|no|no|no|no|yes|no|no|no|no|no|no|no|no|no|
-
-
## Animating Styles and Props
-
-
In the previous section, we explored creating simple animations, understanding shared values, and their application. In this part, we will delve into an alternative method for applying animation styles to components. We'll also examine the distinctions between animating styles versus props and how to manage them using `useAnimatedStyle` and `useAnimatedProps`.
-
-
### Animating Styles with `useAnimatedStyle`
+
In this section, you learned about:
-
The `useAnimatedStyle` hook allows you to define animated styles that can be applied directly to a component's style prop. This approach is particularly useful for smoothly transitioning between different visual states.
-
-
#### Example
-
-
```typescript
-
import { useSharedValue, withSpring, useAnimatedStyle } from 'react-native-reanimated';
-
-
const AnimatedComponent = () => {
-
const opacity = useSharedValue(0);
+
- `Animated` components to define animatable elements.
+
- Shared values as the driving factor of animations using `useSharedValue`.
+
- Accessing and modifying shared values via their `.value` property (e.g., `sv.value = 100;`).
+
- Creating smooth animations by modifying shared values with functions like `withSpring`.
-
// Define the animated styles
-
const animatedStyles = useAnimatedStyle(() => ({
-
opacity: withSpring(opacity.value),
-
}));
+
### What's Next?
-
return <View style={[styles.view, animatedStyles]} />;
-
};
-
```
+
In the next section, you'll explore animating styles and props using `useAnimatedStyle` and `useAnimatedProps` hooks.
-
### Animating Props with `useAnimatedProps`
-
-
While `useAnimatedStyle` is great for animating styles, `useAnimatedProps` allows you to animate component props. This can be useful when the animation involves more than just visual changes.
-
-
#### Example
-
-
```typescript
-
import { useSharedValue, withTiming, useAnimatedProps } from 'react-native-reanimated';
-
-
const AnimatedText = () => {
-
const fontSize = useSharedValue(14);
-
-
// Define animated props
-
const animatedProps = useAnimatedProps(() => ({
-
fontSize: withTiming(fontSize.value + 10),
-
}));
-
-
return <Animated.Text style={styles.text} {...animatedProps}>Hello World</Animated.Text>;
-
};
-
```
-
-
### Key Differences
-
-
- **`useAnimatedStyle`:** Best for animating styles directly. It provides a way to interpolate values and apply them as inline styles.
-
-
- **`useAnimatedProps`:** Ideal for animating props of components that do not support direct style interpolation.
-
-
By understanding these hooks, you can effectively manage animations in your React Native applications, enhancing both performance and user experience.
-
-
## useSharedValue
-
-
`useSharedValue` is a hook that allows you to define shared values within your components.
-
-
### Reference
-
-
```typescript
-
import { useSharedValue } from "react-native-reanimated"
-
-
function App() {
-
const sv = useSharedValue(100)
-
-
// Accessing the shared value
-
console.log(sv.value)
-
-
// Modifying the shared value
-
sv.value += 50
-
}
-
```
-
-
#### Arguments
-
-
##### `initialValue`
-
-
The initial value to store in the shared value. It can be any JavaScript type such as `number`, `string`, or `boolean`, and also includes data structures like `array` and `object`.
-
-
#### Returns
-
-
`useSharedValue` returns a shared value initialized with the provided `initialValue`. You can access this stored data using its `value` property or through `get` and `set` methods.
-
-
##### React Compiler Support
-
-
When utilizing the React Compiler, avoid directly accessing or modifying the `value` property. Instead, use the `get` and `set` methods as they are compliant with React Compiler standards.
-
-
```typescript
-
function App() {
-
const sv = useSharedValue(100)
-
-
const animatedStyle = useAnimatedStyle(() => {
-
"worklet"
-
return { width: sv.get() * 100 }
-
})
-
-
const handlePress = () => {
-
sv.set((value) => value + 1)
-
}
-
}
-
```
-
-
### Remarks
-
-
- Avoid reading or modifying the shared value during a component's render. Accessing the `value` property or using `get`/`set` methods is considered a side-effect, which violates React's Rules of Render.
-
-
- Changes to `sv.value` will update styles and synchronize the shared value across threads without triggering a typical React re-render since it's a plain JavaScript object.
-
-
- Reading `sv.value` on the JavaScript thread may block until the value is fetched from the UI thread. This can be negligible, but if the UI thread is busy or values are read multiple times, synchronization delays might increase.
-
-
- Changes to `sv.value` occur synchronously on the UI thread, while updates on the JavaScript thread are asynchronous. Thus, logging `value` immediately after a change will show the previous value.
-
-
```typescript
-
function App() {
-
const sv = useSharedValue(100) // initially set to 100
-
-
sv.value += 50 // modifying the shared value
-
-
console.log(sv.value) // logs 100 due to asynchronous update on JS thread
-
}
-
```
-
-
- Avoid destructuring assignment with shared values. While valid in JavaScript, it prevents Reanimated from maintaining reactivity.
-
-
```typescript
-
function App() {
-
let { value } = sv // avoid this pattern
-
-
console.log(value) // reading is fine
-
-
value += 50 // does not update styles
-
}
-
```
-
-
- When storing objects in a shared value, ensure to reassign the entire object rather than modifying its properties individually.
-
-
```typescript
-
function App() {
-
const sv = useSharedValue({ x: 0, y: 0 })
-
-
sv.value.x = 50 // loses reactivity
-
-
sv.value = { x: 50, y: 0 } // correct approach
-
}
-
```
-
-
- For large arrays or complex objects in a shared value, use the `.modify` method to alter the existing value without creating a new one.
-
-
```typescript
-
function App() {
-
const sv = useSharedValue([1, 2, 3])
-
-
sv.value.push(1000) // loses reactivity
-
-
sv.value = [...sv.value, 1000] // creates a new copy
-
-
sv.modify((value) => {
-
"worklet"
-
value.push(1000) // correct approach
-
return value
-
})
-
}
-
```
-
-
### Platform Compatibility
-
-
|Android|iOS|Web|
-
|-|-|-|
-
|✅|✅|✅|
-
-
## Contributing Guide for Reanimated
-
-
Thank you for considering contributing to Reanimated. Contributions can range from triaging issues and enhancing documentation to reviewing Pull Requests and submitting code changes.
-
-
### Ways to Contribute
-
-
1. **Handling Open Issues**: Assist by providing detailed descriptions and reproducible examples for existing issues, which helps other contributors understand and address them more efficiently.
-
-
1. **Documentation Assistance**: Improve the documentation by correcting spelling and grammar or expanding explanations. You can also help update outdated pages from Reanimated v2 to the current version. For significant changes, edit locally using Docusaurus and GitHub Pages.
-
-
1. **Reviewing Pull Requests**: Review submitted Pull Requests to identify potential issues or bugs that may have been overlooked, ensuring high-quality contributions.
-
-
1. **Code Contributions**: Submit code through Pull Requests to address issues, fix bugs, or introduce new features. Beginners can start with "good first issue" tasks on GitHub.
-
-
#### Repository Structure
-
-
The Reanimated repository is organized as follows:
-
-
```
-
├── apps
-
│ ├── common-app // Shared source for example apps
-
│ ├── paper-example // React Native app using Old Architecture
-
│ ├── fabric-example // React Native app using New Architecture
-
│ ├── macos-example // React Native for MacOS wrapper
-
│ ├── next-example // Next.js wrapper
-
│ ├── tvos-example // React Native for TVOS wrapper
-
│ └── web-example // React Native for Web wrapper
-
└── packages
-
├── docs-reanimated // Documentation source
-
├── eslint-plugin-reanimated // ESLint plugin source
-
└── react-native-reanimated
-
├── android // Android native code
-
├── apple // iOS native code
-
├── Common // Shared C++ code
-
├── scripts // CI pipeline scripts
-
├── src // Reanimated JS source
-
└── plugin // Babel plugin source
-
```
-
-
### Handling Open Issues
-
-
Providing detailed descriptions and reproducible examples for issues can significantly aid other contributors. Ensure that issues include:
-
-
- A cloneable repository.
-
- Clear reproduction steps.
-
- Comprehensive descriptions.
-
- Relevant stack traces.
-
-
If these details are missing, consider asking the issue owner or providing them yourself to facilitate quicker resolutions.
-
-
### Documentation Assistance
-
-
Improving documentation is a straightforward way to contribute. The Reanimated docs use Docusaurus and GitHub Pages. For minor edits, click **Edit this page** at the bottom of most pages. For more complex changes:
-
-
1. Clone `react-native-reanimated`.
-
1. Navigate to `packages/docs-reanimated`.
-
1. Run `yarn && yarn start` to preview changes locally.
-
-
#### Documentation Structure
-
-
Maintain a consistent structure for clarity and ease of navigation:
-
-
1. **Introduction**: Briefly describe the feature.
-
1. **Reference**: Provide simple usage examples with type definitions.
-
1. **Arguments**: Detail accepted arguments.
-
1. **Returns**: Explain returned values.
-
1. **Example**: Include videos, GIFs, or interactive demos in both light and dark modes.
-
1. **Remarks**: Highlight non-obvious details like platform-specific quirks.
-
1. **Platform Compatibility**: Specify supported platforms.
-
-
#### Writing Style Guide
-
-
- Use active voice for clarity (e.g., "The function receives the arguments").
-
- Write short, clear sentences to aid comprehension.
-
- Organize information into lists for better readability.
-
- Avoid acronyms unless globally recognized (e.g., UI, API).
-
- Use contractions for a conversational tone.
-
-
#### Embedding Interactive Examples
-
-
Use the `InteractiveExample` component with `src` and `component` props to create engaging examples. For videos:
-
-
```typescript
-
import AnimatedKeyboardSrc from '!!raw-loader!@site/src/examples/AnimatedKeyboard';
-
-
<InteractiveExample
-
src={AnimatedKeyboardSrc}
-
component={
-
<ThemedVideo
-
center
-
width={300}
-
sources={{
-
light: '/recordings/useAnimatedKeyboard_light.mov',
-
dark: '/recordings/useAnimatedKeyboard_dark.mov',
-
}}
-
/>
-
}
-
/>;
-
```
-
-
For interactive components:
-
-
```typescript
-
import DecayTrain from '@site/src/examples/DecayTrain';
-
import DecayTrainSrc from '!!raw-loader!@site/src/examples/DecayTrain';
-
-
<InteractiveExample
-
src={DecayTrainSrc}
-
component={<DecayTrain />}
-
label="Grab and drag the train"
-
/>;
-
```
-
-
### Contributing Code
-
-
Submit Pull Requests to address issues or introduce new features. Start with "good first issue" tasks if you're new to open-source contributions.
-
-
#### Working with Android
-
-
1. Install dependencies: `yarn && yarn build`.
-
1. Navigate to `apps/paper-example` and run `yarn start`.
-
1. Open the project in Android Studio at `react-native-reanimated/apps/paper-example/android`.
-
-
#### Working with iOS
-
-
1. Install dependencies: `yarn && yarn build`.
-
1. Run `cd apps/paper-example/ios && bundle install && bundle exec pod install`.
-
1. Start Metro bundler: `cd apps/paper-example && yarn start`.
-
1. Open the project in Xcode at `react-native-reanimated/apps/paper-example/ios/ReanimatedExample.xcworkspace`.
-
-
#### Preparing a Pull Request
-
-
When ready, open a Pull Request using the provided template:
-
-
1. **Summary**: Link relevant issues and describe your changes.
-
1. **Test Plan**: Provide instructions for testing, including code from `EmptyExample` if applicable.
-
-
#### Testing Changes Locally
-
-
To test changes in your project, create a patch with `git diff` or point to a specific commit in `package.json`.
-
-
Thank you for contributing! 🎉
-
-
## Layout Transitions
+
## Layout transitions
Layout transitions enable smooth animations during layout changes, which may involve alterations in size and position. Both aspects can be animated for a seamless experience.
···
This table indicates that all predefined transitions are compatible across Android, iOS, and web platforms.
-
## Debugging Worklets
-
-
### Overview
-
-
This document provides guidance on debugging Reanimated v2 worklets within React Native applications. Due to Reanimated's unique architecture and use of a secondary JavaScript runtime, traditional debugging methods may not function as expected. This article outlines compatible tools and their limitations.
-
-
#### React Native Debugging Tools
-
-
The following tools have been evaluated for compatibility with React Native apps using the Reanimated library:
-
-
- **Chrome Debugger (React Native Debugger):** Utilizes a web worker in your browser to execute app JavaScript code, supporting all available runtimes in React Native.
-
-
- **Chrome DevTools:** Connects to a remote JavaScript runtime, allowing code execution on the device. Note: Not compatible with JSC.
-
-
- **Flipper (Hermes debugger):** Facilitates using Chrome DevTools and offers additional UI inspection tools.
-
-
- **Safari DevTools:** Available only for iOS devices running JSC, similar in functionality to Chrome DevTools by connecting to a remote runtime.
-
-
- **React Developer Tools:** A standalone app for debugging UI through an inspector, monitoring performance, and profiling the application.
-
-
#### JS Context vs. UI Context
-
-
Understanding the distinction between the JavaScript (JS) context and the User Interface (UI) context is crucial. Debugging the regular JS context remains unchanged with Reanimated; however, debugging the UI context specific to Reanimated can be challenging.
-
-
#### Debugging Web Apps
-
-
For web applications, standard browser tools or any preferred debugging tools can be used without issues when employing Reanimated on the web.
-
-
### Compatibility Summary
-
-
|Tool|Platform|JSC|Hermes|V8|
-
|-|-|-|-|-|
-
|Chrome Debugger|Android|⚛️ ✅¹|⚛️ ✅¹|⚛️ ✅¹|
-
||iOS|⚛️ ✅¹|⚛️ ✅¹|N/A|
-
|Chrome DevTools|Android|N/A|⚛️ ✅²|⚛️|
-
||iOS|N/A|⚛️ ✅²|N/A|
-
|Flipper (Hermes debugger)|Android|N/A|⚛️ ✅²|⚛️|
-
||iOS|N/A|⚛️ ✅²|N/A|
-
|Safari DevTools|Android|N/A|N/A|N/A|
-
||iOS|⚛️ ✅|N/A|N/A|
-
|React Developer Tools|Android|⚛️|⚛️|⚛️|
-
||iOS|⚛️|⚛️|N/A|
-
-
¹ - Functions use web implementations, running worklets on the JS thread. Measure and Layout Animations are unavailable. ² - Experimental feature.
-
-
#### Legend
-
-
- ⚛️ ✅: Special features for React Native apps using Reanimated
-
- ⚛️: Standard functionality with no worklet debugging available
-
- N/A: Not applicable in React Native apps
-
-
**Note:** Console logs will always appear in the primary JS runtime as `console.log` on the UI runtime is a wrapper around the JS runtime's function.
-
-
### Tool-Specific Details
-
-
#### Chrome Debugger
-
-
|Platform|JSC|Hermes|V8|
-
|-|-|-|-|
-
|Android|⚛️ ✅|⚛️ ✅|⚛️ ✅|
-
|iOS|⚛️ ✅|⚛️ ✅|N/A|
-
-
**Summary:** Functions use web implementations, running on the JS thread. Measure and Layout Animations are unavailable.
-
-
#### Chrome DevTools
-
-
|Platform|JSC|Hermes|V8|
-
|-|-|-|-|
-
|Android|N/A|⚛️ ✅²|⚛️|
-
|iOS|N/A|⚛️ ✅²|N/A|
-
-
**Summary:** Both contexts can be debugged. This is an experimental feature.
-
-
#### Flipper (Hermes Debugger)
-
-
|Platform|JSC|Hermes|V8|
-
|-|-|-|-|
-
|Android|N/A|⚛️ ✅²|⚛️|
-
|iOS|N/A|⚛️ ✅²|N/A|
-
-
**Summary:** Both contexts can be debugged. This is an experimental feature.
-
-
#### Safari DevTools
-
-
|Platform|JSC|Hermes|V8|
-
|-|-|-|-|
-
|Android|N/A|N/A|N/A|
-
|iOS|⚛️ ✅|N/A|N/A|
-
-
**Summary:** Available only on iOS devices with the JSC engine. Worklet debugging is supported.
-
-
#### React Developer Tools
-
-
|Platform|JSC|Hermes|V8|
-
|-|-|-|-|
-
|Android|⚛️|⚛️|⚛️|
-
|iOS|⚛️|⚛️|N/A|
-
-
**Summary:** Functions as expected, with profiler and layout inspector available.
-
-
#### Additional Notes
-
-
- **Console Logs:** Always appear in the primary JS runtime.
-
-
- **Known Issues:** Include reload failures, breakpoint issues on iOS, unresponsive consoles without animations, and more. These do not affect release builds or debug builds where the debugger is disconnected during a reload.
-
-
*Efforts are ongoing to enhance debugging experiences with Chrome DevTools and Flipper on Hermes.*
-
## Incremental Migration from Reanimated 1 to Reanimated 2
The transition from Reanimated 1 to Reanimated 2 is designed to be incremental. Upon installing Reanimated 2, users can access both the old and new APIs. The latest stable version of Reanimated 1 is included in the same package, with some exceptions due to naming collisions. To maintain a cleaner API in Reanimated 2, methods from Reanimated 1 that had naming conflicts were renamed. This approach aligns with plans to gradually phase out the older API, focusing on fixing existing issues rather than developing new features for it. Consequently, this strategy introduces some breaking changes where certain method names have been altered. However, the list of renamed methods is relatively short and these methods are not frequently used.
···
- **Reanimated 1**: Use `Easing` imported from `react-native-reanimated`.
- **Reanimated 2**: Replace with `EasingNode`.
-
## Getting Started
-
-
The *Fundamentals* section aims to establish a solid understanding of the core concepts of Reanimated, empowering you to explore more complex scenarios independently. This section includes interactive examples, code snippets, and detailed explanations.
-
-
### What is React Native Reanimated?
+
## Reanimated 3.x Overview
-
React Native Reanimated is an advanced animation library developed by Software Mansion. It enables developers to create smooth animations and interactions that run on the UI thread with ease.
-
-
### Quick Start
+
Reanimated 3.x maintains backward compatibility with the Reanimated v2 API, ensuring that all code written for version 2.x functions seamlessly in version 3.x without requiring any modifications. However, it is important to note that Reanimated 3.x completely removes support for the Reanimated v1 API.
-
To begin a new project using Expo:
+
For guidance on migrating from Reanimated 1.x to 2.x, please refer to the specific migration guide titled "Migration from 1.x to 2.x."
-
- **NPM**:
+
## Customizing animations
-
```bash
-
npx create-expo-app@latest my-app -e with-reanimated
-
```
+
The previous section introduced shared values in practice using `withSpring` and `withTiming` functions for creating animations. Now, you're ready to explore customizing these animations further!
-
- **YARN**:
-
```bash
-
yarn create expo-app my-app -e with-reanimated
-
```
+
Reanimated provides three built-in animation functions: `withTiming`, `withSpring`, and `withDecay`. This discussion will focus on the first two, with `withDecay` covered later in the Handling Gestures section.
-
Alternatively, explore examples available on GitHub.
+
Customizing animation behavior in Reanimated is straightforward. You can achieve this by passing a `config` object to the second parameter of either the `withTiming` or `withSpring` function.
-
### Installation
+
### Configuring `withTiming`
-
Adding Reanimated to your project involves three main steps:
+
The `config` parameter for `withTiming` includes two properties: `duration` and `easing`.
-
#### Step 1: Install the Package
+
```typescript
+
import { withTiming, Easing } from "react-native-reanimated"
-
Install the `react-native-reanimated` package from npm:
+
withTiming(sv.value, {
+
duration: 300,
+
easing: Easing.inOut(Easing.quad),
+
})
+
```
-
- **EXPO**:
+
The `duration` parameter specifies the time in milliseconds for the animation to reach its target value (`toValue`). By default, this is set to `300` milliseconds.
-
```bash
-
npx expo install react-native-reanimated
-
```
+
The `easing` parameter allows you to refine how the animation progresses over time. For instance, it can start slowly, accelerate, and then slow down again towards the end. The default easing function is `Easing.inOut(Easing.quad)`.
-
- **NPM**:
+
To understand its impact, compare a `linear` easing with the default easing. Reanimated offers several predefined easing functions that you can experiment with in an interactive playground or refer to the full `withTiming` API documentation.
-
```bash
-
npm install react-native-reanimated
-
```
+
### Configuring `withSpring`
-
- **YARN**:
-
```bash
-
yarn add react-native-reanimated
-
```
+
Unlike `withTiming`, `withSpring` is physics-based and simulates real-world spring dynamics, making animations appear more realistic.
-
#### Step 2: Add Reanimated's Babel Plugin
+
When adjusting springs, focus on these three properties: `mass`, `stiffness` (also known as *tension*), and `damping` (also known as *friction*).
-
Include the `react-native-reanimated/plugin` in your `babel.config.js`:
+
```typescript
+
import { withSpring } from "react-native-reanimated"
-
```javascript
-
module.exports = {
-
presets: [
-
// existing presets
-
],
-
plugins: [
-
// other plugins,
-
"react-native-reanimated/plugin",
-
],
-
}
+
withSpring(sv.value, {
+
mass: 1,
+
stiffness: 100,
+
damping: 10,
+
})
```
-
**Caution**: Ensure that `react-native-reanimated/plugin` is the last plugin listed.
+
The `mass` of a spring affects how difficult it is to move an object and bring it to a stop. It adds inertia to the movement. A higher mass results in a more sluggish motion compared to the default.
-
#### Step 3: Wrap Metro Config with Reanimated Wrapper (Recommended)
+
`Stiffness` determines the bounciness of the spring, akin to comparing a steel spring (high stiffness) with one made from soft plastic (low stiffness).
-
Modify your `metro.config.js` to wrap the existing configuration using `wrapWithReanimatedMetroConfig`:
+
`Damping` describes how quickly the animation concludes. Higher damping means the spring will settle faster. For example, consider a spring bouncing in air versus underwater; a vacuum would have zero friction and thus no damping.
-
```javascript
-
// metro.config.js
-
const {
-
wrapWithReanimatedMetroConfig,
-
} = require("react-native-reanimated/metro-config")
+
Reanimated includes additional properties for customizing spring animations, which you can explore in an interactive playground or through the full `withSpring` API documentation.
-
const config = {
-
// Your existing Metro configuration options
-
}
+
### Summary
-
module.exports = wrapWithReanimatedMetroConfig(config)
-
```
+
This section covered how to customize `withTiming` and `withSpring` animation functions:
-
#### Step 4: Clear Metro Bundler Cache (Recommended)
+
- Both functions accept a `config` object as their second parameter.
+
- You can modify `withTiming` using `duration` and `easing`. Reanimated provides an `Easing` module for convenience.
+
- Key properties for adjusting `withSpring` include `mass`, `stiffness`, and `damping`.
-
- **EXPO**:
+
### What's Next?
-
```bash
-
npx expo start -c
-
```
+
In the next section, you'll learn about animation modifiers like `withSequence` and `withRepeat`, enabling more complex and engaging animations.
-
- **NPM**:
+
## Custom animations
-
```bash
-
npm start -- --reset-cache
-
```
+
Custom animations provide full control over entering/exiting animations and layout transitions. However, they can be complex to understand and maintain. It's advisable to start with predefined presets before using custom animations.
-
- **YARN**:
-
```bash
-
yarn start --reset-cache
-
```
+
### Reference
-
#### Expo Development Build
-
-
For an Expo development build, update the native code in `ios` and `android` directories by running:
-
-
```bash
-
npx expo prebuild
+
```typescript
+
function CustomAnimation(values: any) {
+
"worklet"
+
const animations = {
+
// Define your animations here
+
}
+
const initialValues = {
+
// Set initial values for animations
+
}
+
const callback = (finished: boolean) => {
+
// Optional callback when the layout animation ends
+
}
+
return {
+
initialValues,
+
animations,
+
callback,
+
}
+
}
```
-
#### Platform-Specific Setup
+
### Custom Exiting Animation
-
##### Android
+
#### Arguments
-
No additional setup is required.
+
- `values`: Contains information about where the view was displayed and its dimensions.
+
- `currentOriginX`: X coordinate of the top-left corner in the parent's coordinate system.
+
- `currentOriginY`: Y coordinate of the top-left corner in the parent's coordinate system.
+
- `currentWidth`: View's width.
+
- `currentHeight`: View's height.
+
- `currentBorderRadius`: View's border radius.
+
- `currentGlobalOriginX`: X coordinate of the top-left corner in the global coordinate system.
+
- `currentGlobalOriginY`: Y coordinate of the top-left corner in the global coordinate system.
-
##### iOS
+
#### Example
-
Before running your app on iOS, install pods with:
-
-
```bash
-
cd ios && pod install && cd ..
+
```typescript
+
const customExiting = (values: any) => {
+
"worklet"
+
const animations = {
+
originX: withTiming(2 * WIDTH, { duration: 3000 }),
+
opacity: withTiming(0, { duration: 2000 }),
+
transform: [{ scale: withTiming(0.2, { duration: 3500 }) }],
+
}
+
const initialValues = {
+
originX: values.currentOriginX,
+
opacity: 1,
+
transform: [{ scale: 1 }],
+
}
+
return {
+
initialValues,
+
animations,
+
}
+
}
```
-
##### Web
+
### Custom Entering Animation
-
For web-targeted apps using react-native-web, it's recommended to use Expo. Install and add `@babel/plugin-proposal-export-namespace-from` Babel plugin in your `babel.config.js`:
+
#### Arguments
-
- **EXPO**:
+
- `values`: Contains information about where the view wants to be displayed and its dimensions.
+
- `targetOriginX`: X coordinate of the top-left corner in the parent's coordinate system.
+
- `targetOriginY`: Y coordinate of the top-left corner in the parent's coordinate system.
+
- `targetWidth`: View's width.
+
- `targetHeight`: View's height.
+
- `targetBorderRadius`: View's border radius.
+
- `targetGlobalOriginX`: X coordinate of the top-left corner in the global coordinate system.
+
- `targetGlobalOriginY`: Y coordinate of the top-left corner in the global coordinate system.
-
```bash
-
npx expo install @babel/plugin-proposal-export-namespace-from
-
```
+
#### Example
-
- **NPM**:
-
-
```bash
-
npm install @babel/plugin-proposal-export-namespace-from
-
```
-
-
- **YARN**:
-
```bash
-
yarn add @babel/plugin-proposal-export-namespace-from
-
```
-
-
Ensure your `babel.config.js` includes:
-
-
```javascript
-
module.exports = {
-
presets: [
-
// existing presets
-
],
-
plugins: [
-
"@babel/plugin-proposal-export-namespace-from",
-
"react-native-reanimated/plugin",
-
],
+
```typescript
+
const customEntering = (targetValues: any) => {
+
"worklet"
+
const animations = {
+
originX: withTiming(targetValues.targetOriginX, { duration: 3000 }),
+
opacity: withTiming(1, { duration: 2000 }),
+
borderRadius: withDelay(1500, withTiming(40, { duration: 3000 })),
+
transform: [
+
{ rotate: withTiming("0deg", { duration: 4000 }) },
+
{ scale: withTiming(1, { duration: 3500 }) },
+
],
+
}
+
const initialValues = {
+
originX: -WIDTH,
+
opacity: 0,
+
borderRadius: 10,
+
transform: [{ rotate: "90deg" }, { scale: 0.2 }],
+
}
+
return {
+
initialValues,
+
animations,
+
}
```
-
**Note**: The `react-native-reanimated/plugin` should be listed last.
+
### Custom Layout Transition
-
For more advanced scenarios, such as using Reanimated with `webpack` or `Next.js`, refer to the separate Web Support guide.
+
#### Arguments
-
## Reanimated 3.x Overview
+
- `values`: Contains before and after information about the view's origin and dimensions.
+
- `targetOriginX`: X coordinate of the top-left corner in the parent's coordinate system.
+
- `targetOriginY`: Y coordinate of the top-left corner in the parent's coordinate system.
+
- `targetWidth`: View's width.
+
- `targetHeight`: View's height.
+
- `targetBorderRadius`: View's border radius.
+
- `targetGlobalOriginX`: X coordinate of the top-left corner in the global coordinate system.
+
- `targetGlobalOriginY`: Y coordinate of the top-left corner in the global coordinate system.
+
- `currentOriginX`: X coordinate of the top-left corner in the parent's coordinate system (before).
+
- `currentOriginY`: Y coordinate of the top-left corner in the parent's coordinate system (before).
+
- `currentWidth`: View's width (before).
+
- `currentHeight`: View's height (before).
+
- `currentBorderRadius`: View's border radius (before).
+
- `currentGlobalOriginX`: X coordinate of the top-left corner in the global coordinate system (before).
+
- `currentGlobalOriginY`: Y coordinate of the top-left corner in the global coordinate system (before).
-
Reanimated 3.x maintains backward compatibility with the Reanimated v2 API, ensuring that all code written for version 2.x functions seamlessly in version 3.x without requiring any modifications. However, it is important to note that Reanimated 3.x completely removes support for the Reanimated v1 API.
+
#### Example
-
For guidance on migrating from Reanimated 1.x to 2.x, please refer to the specific migration guide titled "Migration from 1.x to 2.x."
+
```typescript
+
const customLayoutTransition = (values: any) => {
+
"worklet"
+
return {
+
animations: {
+
originX: withTiming(values.targetOriginX, { duration: 1000 }),
+
originY: withDelay(
+
1000,
+
withTiming(values.targetOriginY, { duration: 1000 })
+
),
+
width: withSpring(values.targetWidth),
+
height: withSpring(values.targetHeight),
+
},
+
initialValues: {
+
originX: values.currentOriginX,
+
originY: values.currentOriginY,
+
width: values.currentWidth,
+
height: values.currentHeight,
+
},
+
}
+
}
+
```
-
```markdown
-
# Animations (Version: 3.x)
+
### Remarks
-
## withTiming
+
- Each Reanimated component has a shared value that keeps the current animations assigned to it. If you start a new animation for a specific property without providing an initial value, the initial value will be taken from the last animation assigned to the component. The exception is the `Entering` animation, as previous animation values are unavailable.
-
`withTiming` allows for creating animations based on a specified duration and easing function.
+
### Platform Compatibility
-
## withSpring
+
|Android|iOS|Web|
+
|-|-|-|
+
|✅|✅|❌|
-
`withSpring` enables the creation of spring-based animations, providing a natural motion effect.
-
-
## withDecay
-
-
`withDecay` creates animations that simulate objects in motion experiencing friction. The animation begins at a given velocity and gradually slows down according to a specified deceleration rate until it comes to a stop.
-
-
## withSequence
-
-
`withSequence` is an animation modifier used for executing multiple animations one after another in sequence.
-
-
## withRepeat
-
-
`withRepeat` is an animation modifier that allows an animation to be repeated a certain number of times or indefinitely.
-
-
## withDelay
-
-
`withDelay` is an animation modifier that introduces a delay before starting the animation.
-
-
## withClamp
-
-
`withClamp` is an animation modifier used to restrict the movement range of an animation, ensuring it stays within predefined limits.
-
```
-
-
## Testing with Jest and Reanimated
+
## Testing with Jest
Reanimated provides a testing API based on Jest to facilitate the mocking of web-based animations. This guide outlines how to set up and use these tools effectively.
···
- [@testing-library/react-native](https://testing-library.com/docs/native-testing-library/intro)
- [@testing-library/react-hooks](https://testing-library.com/docs/react-hooks-testing-library/intro) - Useful for dealing with hooks.
-
## Custom Animations
+
## withTiming
-
Custom animations provide full control over entering/exiting animations and layout transitions. However, they can be complex to understand and maintain. It's advisable to start with predefined presets before using custom animations.
+
`withTiming` enables you to create animations based on duration and easing functions.
### Reference
```typescript
-
function CustomAnimation(values: any) {
-
"worklet"
-
const animations = {
-
// Define your animations here
-
}
-
const initialValues = {
-
// Set initial values for animations
-
}
-
const callback = (finished: boolean) => {
-
// Optional callback when the layout animation ends
-
}
-
return {
-
initialValues,
-
animations,
-
callback,
-
}
+
import { withTiming } from "react-native-reanimated"
+
+
function App() {
+
sv.value = withTiming(0)
+
// ...
```
-
-
### Custom Exiting Animation
#### Arguments
-
- `values`: Contains information about where the view was displayed and its dimensions.
-
- `currentOriginX`: X coordinate of the top-left corner in the parent's coordinate system.
-
- `currentOriginY`: Y coordinate of the top-left corner in the parent's coordinate system.
-
- `currentWidth`: View's width.
-
- `currentHeight`: View's height.
-
- `currentBorderRadius`: View's border radius.
-
- `currentGlobalOriginX`: X coordinate of the top-left corner in the global coordinate system.
-
- `currentGlobalOriginY`: Y coordinate of the top-left corner in the global coordinate system.
+
##### `toValue`
-
#### Example
+
The target value for the animation. Supported categories include:
-
```typescript
-
const customExiting = (values: any) => {
-
"worklet"
-
const animations = {
-
originX: withTiming(2 * WIDTH, { duration: 3000 }),
-
opacity: withTiming(0, { duration: 2000 }),
-
transform: [{ scale: withTiming(0.2, { duration: 3500 }) }],
-
}
-
const initialValues = {
-
originX: values.currentOriginX,
-
opacity: 1,
-
transform: [{ scale: 1 }],
-
}
-
return {
-
initialValues,
-
animations,
-
}
-
}
-
```
+
- **Numbers**: Can be a number or a string representation of a number.
+
- **Suffixed Numbers**: Strings that combine numbers and units (e.g., `"5.5%"`, `"90deg"`, `"3bananas"`). Ensure no space between the number and suffix, with the suffix containing only basic English letters.
+
- **Colors**:
+
- Hexadecimal integer: e.g., `0xff1234`
+
- RGB: e.g., `"rgb(100, 50, 0)"`
+
- RGBA: e.g., `"rgba(255, 105, 180, 0.5)"`
+
- RGB Hexadecimal: e.g., `"#53575E"`
+
- HSL: e.g., `"hsl(0, 50%, 50%)"`
+
- Named colors: e.g., `"dodgerblue"`
+
- **Objects**: Objects with properties that will be animated individually.
+
- **Arrays**: Arrays of numbers where each value is animated separately.
+
- **Transformation Matrix**: An array of exactly 16 numerical values treated as a transformation matrix, decomposed into rotation, scale, and translation for animation.
-
### Custom Entering Animation
+
Ensure `toValue` and the shared value being animated are of the same category (e.g., you cannot animate `width` from `100px` to `50%`).
-
#### Arguments
+
##### `config` (Optional)
-
- `values`: Contains information about where the view wants to be displayed and its dimensions.
-
- `targetOriginX`: X coordinate of the top-left corner in the parent's coordinate system.
-
- `targetOriginY`: Y coordinate of the top-left corner in the parent's coordinate system.
-
- `targetWidth`: View's width.
-
- `targetHeight`: View's height.
-
- `targetBorderRadius`: View's border radius.
-
- `targetGlobalOriginX`: X coordinate of the top-left corner in the global coordinate system.
-
- `targetGlobalOriginY`: Y coordinate of the top-left corner in the global coordinate system.
+
The configuration for timing animations. Available properties:
+
+
|Name|Type|Default|Description|
+
|-|-|-|-|
+
|duration|`number`|300|Length of the animation in milliseconds.|
+
|easing|`Easing`|`Easing.inOut(Easing.quad)`|An easing function defining the animation curve.|
+
|reduceMotion|`ReduceMotion`|`ReduceMotion.System`|Determines how the animation responds to reduced motion settings on devices.|
+
+
###### `Easing`
+
+
The `easing` parameter allows fine-tuning of the animation over time, such as starting with fast acceleration and slowing down towards the end.
+
+
Reanimated provides various easing functions in the `Easing` module. You can visualize common easing functions at [easings.net](http://easings.net/).
-
#### Example
+
Use built-in easings by passing them to the `withTiming` config:
```typescript
-
const customEntering = (targetValues: any) => {
-
"worklet"
-
const animations = {
-
originX: withTiming(targetValues.targetOriginX, { duration: 3000 }),
-
opacity: withTiming(1, { duration: 2000 }),
-
borderRadius: withDelay(1500, withTiming(40, { duration: 3000 })),
-
transform: [
-
{ rotate: withTiming("0deg", { duration: 4000 }) },
-
{ scale: withTiming(1, { duration: 3500 }) },
-
],
-
}
-
const initialValues = {
-
originX: -WIDTH,
-
opacity: 0,
-
borderRadius: 10,
-
transform: [{ rotate: "90deg" }, { scale: 0.2 }],
-
}
-
return {
-
initialValues,
-
animations,
-
}
-
}
+
import { Easing } from "react-native-reanimated"
+
+
withTiming(sv.value, {
+
easing: Easing.bounce,
+
})
```
-
### Custom Layout Transition
+
Available functions include:
-
#### Arguments
+
- `back`: Animation where the object slightly moves back before moving forward.
+
- `bezier(x1: number, y1: number, x2: number, y2: number)`: Cubic bezier curve.
+
- `bounce`: Bouncing animation.
+
- `circle`: Circular function.
+
- `cubic`: Cubic function.
+
- `ease`: Simple inertial animation.
+
- `elastic(bounciness?: number)`: Spring interaction.
+
- `exp`: Exponential function.
+
- `linear`: Linear function.
+
- `poly(n: number)`: Higher power functions like quartic, quintic.
+
- `quad`: Quadratic function.
+
- `sin`: Sinusoidal function.
+
+
Helpers to modify easing functions:
+
+
- `in(easing: EasingFunction)`: Runs an easing function forwards.
+
- `inOut(easing: EasingFunction)`: Symmetrical easing function.
+
- `out(easing: EasingFunction)`: Runs an easing function backwards.
+
+
##### `callback` (Optional)
+
+
A function called upon animation completion. If the animation is canceled, it receives `false`; otherwise, it receives `true`.
-
- `values`: Contains before and after information about the view's origin and dimensions.
-
- `targetOriginX`: X coordinate of the top-left corner in the parent's coordinate system.
-
- `targetOriginY`: Y coordinate of the top-left corner in the parent's coordinate system.
-
- `targetWidth`: View's width.
-
- `targetHeight`: View's height.
-
- `targetBorderRadius`: View's border radius.
-
- `targetGlobalOriginX`: X coordinate of the top-left corner in the global coordinate system.
-
- `targetGlobalOriginY`: Y coordinate of the top-left corner in the global coordinate system.
-
- `currentOriginX`: X coordinate of the top-left corner in the parent's coordinate system (before).
-
- `currentOriginY`: Y coordinate of the top-left corner in the parent's coordinate system (before).
-
- `currentWidth`: View's width (before).
-
- `currentHeight`: View's height (before).
-
- `currentBorderRadius`: View's border radius (before).
-
- `currentGlobalOriginX`: X coordinate of the top-left corner in the global coordinate system (before).
-
- `currentGlobalOriginY`: Y coordinate of the top-left corner in the global coordinate system (before).
+
#### Returns
-
#### Example
+
`withTiming` returns an animation object representing the current state of the animation. It can be assigned to a shared value or used in a style object from `useAnimatedStyle`.
-
```typescript
-
const customLayoutTransition = (values: any) => {
-
"worklet"
-
return {
-
animations: {
-
originX: withTiming(values.targetOriginX, { duration: 1000 }),
-
originY: withDelay(
-
1000,
-
withTiming(values.targetOriginY, { duration: 1000 })
-
),
-
width: withSpring(values.targetWidth),
-
height: withSpring(values.targetHeight),
-
},
-
initialValues: {
-
originX: values.currentOriginX,
-
originY: values.currentOriginY,
-
width: values.currentWidth,
-
height: values.currentHeight,
-
},
-
}
-
}
-
```
+
### Example
### Remarks
-
- Each Reanimated component has a shared value that keeps the current animations assigned to it. If you start a new animation for a specific property without providing an initial value, the initial value will be taken from the last animation assigned to the component. The exception is the `Entering` animation, as previous animation values are unavailable.
+
- The callback passed as the third argument is automatically workletized and executed on the UI thread.
### Platform Compatibility
|Android|iOS|Web|
|-|-|-|
-
|✅|✅|❌|
+
|✅|✅|✅|
## useAnimatedProps
···
import "raf/polyfill"
```
-
```markdown
-
## About
-
-
### What is Reanimated Babel Plugin?
-
-
The Reanimated Babel Plugin is a tool designed to enhance the performance of animations in React Native applications. It works by transforming animation code during the build process, allowing for more efficient execution on mobile devices. By leveraging this plugin, developers can create smooth and responsive animations that run directly on the UI thread, bypassing JavaScript's limitations.
-
```
-
## React Native Reanimated: List Layout Animations (Version 3.x)
### Overview
···
- **Remarks**
- **Platform compatibility**
-
## withTiming
-
-
`withTiming` enables you to create animations based on duration and easing functions.
-
-
### Reference
-
-
```typescript
-
import { withTiming } from "react-native-reanimated"
-
-
function App() {
-
sv.value = withTiming(0)
-
// ...
-
}
-
```
-
-
#### Arguments
-
-
##### `toValue`
-
-
The target value for the animation. Supported categories include:
-
-
- **Numbers**: Can be a number or a string representation of a number.
-
- **Suffixed Numbers**: Strings that combine numbers and units (e.g., `"5.5%"`, `"90deg"`, `"3bananas"`). Ensure no space between the number and suffix, with the suffix containing only basic English letters.
-
- **Colors**:
-
- Hexadecimal integer: e.g., `0xff1234`
-
- RGB: e.g., `"rgb(100, 50, 0)"`
-
- RGBA: e.g., `"rgba(255, 105, 180, 0.5)"`
-
- RGB Hexadecimal: e.g., `"#53575E"`
-
- HSL: e.g., `"hsl(0, 50%, 50%)"`
-
- Named colors: e.g., `"dodgerblue"`
-
- **Objects**: Objects with properties that will be animated individually.
-
- **Arrays**: Arrays of numbers where each value is animated separately.
-
- **Transformation Matrix**: An array of exactly 16 numerical values treated as a transformation matrix, decomposed into rotation, scale, and translation for animation.
-
-
Ensure `toValue` and the shared value being animated are of the same category (e.g., you cannot animate `width` from `100px` to `50%`).
-
-
##### `config` (Optional)
-
-
The configuration for timing animations. Available properties:
-
-
|Name|Type|Default|Description|
-
|-|-|-|-|
-
|duration|`number`|300|Length of the animation in milliseconds.|
-
|easing|`Easing`|`Easing.inOut(Easing.quad)`|An easing function defining the animation curve.|
-
|reduceMotion|`ReduceMotion`|`ReduceMotion.System`|Determines how the animation responds to reduced motion settings on devices.|
-
-
###### `Easing`
-
-
The `easing` parameter allows fine-tuning of the animation over time, such as starting with fast acceleration and slowing down towards the end.
-
-
Reanimated provides various easing functions in the `Easing` module. You can visualize common easing functions at [easings.net](http://easings.net/).
-
-
Use built-in easings by passing them to the `withTiming` config:
-
-
```typescript
-
import { Easing } from "react-native-reanimated"
-
-
withTiming(sv.value, {
-
easing: Easing.bounce,
-
})
-
```
-
-
Available functions include:
-
-
- `back`: Animation where the object slightly moves back before moving forward.
-
- `bezier(x1: number, y1: number, x2: number, y2: number)`: Cubic bezier curve.
-
- `bounce`: Bouncing animation.
-
- `circle`: Circular function.
-
- `cubic`: Cubic function.
-
- `ease`: Simple inertial animation.
-
- `elastic(bounciness?: number)`: Spring interaction.
-
- `exp`: Exponential function.
-
- `linear`: Linear function.
-
- `poly(n: number)`: Higher power functions like quartic, quintic.
-
- `quad`: Quadratic function.
-
- `sin`: Sinusoidal function.
-
-
Helpers to modify easing functions:
-
-
- `in(easing: EasingFunction)`: Runs an easing function forwards.
-
- `inOut(easing: EasingFunction)`: Symmetrical easing function.
-
- `out(easing: EasingFunction)`: Runs an easing function backwards.
-
-
##### `callback` (Optional)
-
-
A function called upon animation completion. If the animation is canceled, it receives `false`; otherwise, it receives `true`.
-
-
#### Returns
-
-
`withTiming` returns an animation object representing the current state of the animation. It can be assigned to a shared value or used in a style object from `useAnimatedStyle`.
-
-
### Example
-
-
### Remarks
-
-
- The callback passed as the third argument is automatically workletized and executed on the UI thread.
-
-
### Platform Compatibility
-
-
|Android|iOS|Web|
-
|-|-|-|
-
|✅|✅|✅|
-
-
## Getting Started
+
## Getting started
The *Fundamentals* section aims to establish a solid understanding of the core concepts of Reanimated, empowering you to explore more complex scenarios independently. This section includes interactive examples, code snippets, and detailed explanations.
···
|-|-|-|
|✅|✅|✅|
-
```markdown
-
# Overview
+
## Getting started
+
+
The *Fundamentals* section aims to establish a solid understanding of the core concepts of Reanimated, empowering you to explore more complex scenarios independently. This section includes interactive examples, code snippets, and detailed explanations.
+
+
### What is React Native Reanimated?
+
+
React Native Reanimated is an advanced animation library developed by Software Mansion. It enables developers to create smooth animations and interactions that run on the UI thread with ease.
+
+
### Quick Start
+
+
To begin a new project using Expo:
+
+
- **NPM**:
+
+
```bash
+
npx create-expo-app@latest my-app -e with-reanimated
+
```
-
The Shared Element Transition feature is currently in the experimental stage and should not be used in production environments at this time. Feedback from users is being sought to enhance its development and implementation.
+
- **YARN**:
+
```bash
+
yarn create expo-app my-app -e with-reanimated
+
```
-
## Key Points
+
Alternatively, explore examples available on GitHub.
-
- **Experimental Status**: The feature is still under development and testing.
-
- **Not for Production Use**: It's advised against using it in live applications until further notice.
-
- **Feedback Requested**: User input is crucial for refining the feature.
+
### Installation
+
+
Adding Reanimated to your project involves three main steps:
+
+
#### Step 1: Install the Package
+
+
Install the `react-native-reanimated` package from npm:
+
+
- **EXPO**:
+
+
```bash
+
npx expo install react-native-reanimated
+
```
+
+
- **NPM**:
+
+
```bash
+
npm install react-native-reanimated
+
```
+
+
- **YARN**:
+
```bash
+
yarn add react-native-reanimated
+
```
+
+
#### Step 2: Add Reanimated's Babel Plugin
+
+
Include the `react-native-reanimated/plugin` in your `babel.config.js`:
+
+
```javascript
+
module.exports = {
+
presets: [
+
// existing presets
+
],
+
plugins: [
+
// other plugins,
+
"react-native-reanimated/plugin",
+
],
+
}
```
-
## Customizing Animations
+
**Caution**: Ensure that `react-native-reanimated/plugin` is the last plugin listed.
-
The previous section introduced shared values in practice using `withSpring` and `withTiming` functions for creating animations. Now, you're ready to explore customizing these animations further!
+
#### Step 3: Wrap Metro Config with Reanimated Wrapper (Recommended)
-
Reanimated provides three built-in animation functions: `withTiming`, `withSpring`, and `withDecay`. This discussion will focus on the first two, with `withDecay` covered later in the Handling Gestures section.
+
Modify your `metro.config.js` to wrap the existing configuration using `wrapWithReanimatedMetroConfig`:
-
Customizing animation behavior in Reanimated is straightforward. You can achieve this by passing a `config` object to the second parameter of either the `withTiming` or `withSpring` function.
+
```javascript
+
// metro.config.js
+
const {
+
wrapWithReanimatedMetroConfig,
+
} = require("react-native-reanimated/metro-config")
-
### Configuring `withTiming`
+
const config = {
+
// Your existing Metro configuration options
+
}
-
The `config` parameter for `withTiming` includes two properties: `duration` and `easing`.
+
module.exports = wrapWithReanimatedMetroConfig(config)
+
```
-
```typescript
-
import { withTiming, Easing } from "react-native-reanimated"
+
#### Step 4: Clear Metro Bundler Cache (Recommended)
+
+
- **EXPO**:
+
+
```bash
+
npx expo start -c
+
```
+
+
- **NPM**:
+
+
```bash
+
npm start -- --reset-cache
+
```
+
+
- **YARN**:
+
```bash
+
yarn start --reset-cache
+
```
-
withTiming(sv.value, {
-
duration: 300,
-
easing: Easing.inOut(Easing.quad),
-
})
+
#### Expo Development Build
+
+
For an Expo development build, update the native code in `ios` and `android` directories by running:
+
+
```bash
+
npx expo prebuild
```
-
The `duration` parameter specifies the time in milliseconds for the animation to reach its target value (`toValue`). By default, this is set to `300` milliseconds.
+
#### Platform-Specific Setup
-
The `easing` parameter allows you to refine how the animation progresses over time. For instance, it can start slowly, accelerate, and then slow down again towards the end. The default easing function is `Easing.inOut(Easing.quad)`.
+
##### Android
-
To understand its impact, compare a `linear` easing with the default easing. Reanimated offers several predefined easing functions that you can experiment with in an interactive playground or refer to the full `withTiming` API documentation.
+
No additional setup is required.
-
### Configuring `withSpring`
+
##### iOS
-
Unlike `withTiming`, `withSpring` is physics-based and simulates real-world spring dynamics, making animations appear more realistic.
+
Before running your app on iOS, install pods with:
-
When adjusting springs, focus on these three properties: `mass`, `stiffness` (also known as *tension*), and `damping` (also known as *friction*).
+
```bash
+
cd ios && pod install && cd ..
+
```
-
```typescript
-
import { withSpring } from "react-native-reanimated"
+
##### Web
-
withSpring(sv.value, {
-
mass: 1,
-
stiffness: 100,
-
damping: 10,
-
})
-
```
+
For web-targeted apps using react-native-web, it's recommended to use Expo. Install and add `@babel/plugin-proposal-export-namespace-from` Babel plugin in your `babel.config.js`:
-
The `mass` of a spring affects how difficult it is to move an object and bring it to a stop. It adds inertia to the movement. A higher mass results in a more sluggish motion compared to the default.
+
- **EXPO**:
-
`Stiffness` determines the bounciness of the spring, akin to comparing a steel spring (high stiffness) with one made from soft plastic (low stiffness).
+
```bash
+
npx expo install @babel/plugin-proposal-export-namespace-from
+
```
-
`Damping` describes how quickly the animation concludes. Higher damping means the spring will settle faster. For example, consider a spring bouncing in air versus underwater; a vacuum would have zero friction and thus no damping.
+
- **NPM**:
-
Reanimated includes additional properties for customizing spring animations, which you can explore in an interactive playground or through the full `withSpring` API documentation.
+
```bash
+
npm install @babel/plugin-proposal-export-namespace-from
+
```
-
### Summary
+
- **YARN**:
+
```bash
+
yarn add @babel/plugin-proposal-export-namespace-from
+
```
-
This section covered how to customize `withTiming` and `withSpring` animation functions:
+
Ensure your `babel.config.js` includes:
-
- Both functions accept a `config` object as their second parameter.
-
- You can modify `withTiming` using `duration` and `easing`. Reanimated provides an `Easing` module for convenience.
-
- Key properties for adjusting `withSpring` include `mass`, `stiffness`, and `damping`.
+
```javascript
+
module.exports = {
+
presets: [
+
// existing presets
+
],
+
plugins: [
+
"@babel/plugin-proposal-export-namespace-from",
+
"react-native-reanimated/plugin",
+
],
+
}
+
```
-
### What's Next?
+
**Note**: The `react-native-reanimated/plugin` should be listed last.
-
In the next section, you'll learn about animation modifiers like `withSequence` and `withRepeat`, enabling more complex and engaging animations.
+
For more advanced scenarios, such as using Reanimated with `webpack` or `Next.js`, refer to the separate Web Support guide.
## withSpring
···
|-|-|-|
|✅|✅|✅|
-
## createWorkletRuntime
+
## Web Support
+
+
Reanimated can be launched in a web browser, with all functionalities implemented purely in JavaScript. This may result in lower animation efficiency compared to native implementations.
+
+
### Step 1: Install the Package
+
+
Install `@babel/plugin-proposal-export-namespace-from` using one of the following package managers:
+
+
- **EXPO**
+
+
```bash
+
npx expo install @babel/plugin-proposal-export-namespace-from
+
```
+
+
- **NPM**
-
The `createWorkletRuntime` function is designed to establish a new JavaScript runtime environment specifically for executing worklets, potentially on threads distinct from those used by standard JavaScript or the UI. This functionality is primarily intended for use by third-party libraries that require integration with worklets.
+
```bash
+
npm install @babel/plugin-proposal-export-namespace-from
+
```
-
Upon invocation, `createWorkletRuntime` returns an object representing the newly created runtime. This object must be communicated to the C++ side via the JavaScript Interface (JSI) to facilitate subsequent operations and interactions within the worklet environment.
+
- **YARN**
+
```bash
+
yarn add @babel/plugin-proposal-export-namespace-from
+
```
-
## Animating Styles and Props
+
### Step 2: Add Plugins to Config File
+
+
Update your `babel.config.js` by adding the following plugins:
+
+
```javascript
+
module.exports = {
+
presets: [
+
// Existing presets...
+
],
+
plugins: [
+
...,
+
'@babel/plugin-proposal-export-namespace-from',
+
'react-native-reanimated/plugin', // Ensure this is listed last
+
],
+
};
+
```
+
+
**Caution:** Make sure `react-native-reanimated/plugin` is the last plugin in the list.
+
+
### Step 3: Launch Your App
+
+
To start a playground app in the browser, use:
+
+
```bash
+
yarn web
+
```
+
+
For example applications from the Reanimated repository, execute these commands at the root of the repository:
+
+
```bash
+
yarn && yarn build
+
```
+
+
Then navigate to `apps/web-example` and run:
+
+
```bash
+
yarn start
+
```
+
+
### Webpack Support
+
+
To use Reanimated in a Webpack app, adjust your configuration as follows:
+
+
Example Webpack config with Reanimated support:
+
+
```javascript
+
const HtmlWebpackPlugin = require("html-webpack-plugin")
+
const webpack = require("webpack")
+
+
module.exports = {
+
entry: ["babel-polyfill", "./index.js"],
+
plugins: [
+
new HtmlWebpackPlugin({
+
filename: "index.html",
+
template: "./index.html",
+
}),
+
new webpack.EnvironmentPlugin({ JEST_WORKER_ID: null }),
+
new webpack.DefinePlugin({ process: { env: {} } }),
+
],
+
module: {
+
rules: [
+
{
+
test: /\.(js|jsx)$/,
+
use: {
+
loader: "babel-loader",
+
options: {
+
presets: [
+
"@babel/preset-react",
+
{ plugins: ["@babel/plugin-proposal-class-properties"] },
+
],
+
},
+
},
+
},
+
],
+
},
+
resolve: {
+
alias: { "react-native$": "react-native-web" },
+
extensions: [".web.js", ".js"],
+
},
+
}
+
```
+
+
### Web Without the Babel Plugin
+
+
Reanimated can be used without its Babel plugin by manually passing dependency arrays to hooks. This approach is valid for both web and native platforms.
+
+
Ensure these hooks include a dependency array as their last argument:
+
+
- `useDerivedValue`
+
- `useAnimatedStyle`
+
- `useAnimatedProps`
+
- `useAnimatedReaction`
+
+
Example usage:
+
+
```javascript
+
const sv = useSharedValue(0)
+
const dv = useDerivedValue(
+
() => sv.value + 1,
+
[sv] // dependency array here
+
)
+
```
+
+
**Caution:** Pass the root dependency (`sv`) rather than `sv.value`.
+
+
Babel users must still install the `@babel/plugin-proposal-class-properties` plugin.
+
+
#### ESLint Support
+
+
To add ESLint support for Reanimated hooks, update your ESLint configuration:
+
+
```json
+
{
+
"rules": {
+
"react-hooks/exhaustive-deps": [
+
"error",
+
{
+
"additionalHooks": "(useAnimatedStyle|useDerivedValue|useAnimatedProps)"
+
}
+
]
+
}
+
}
+
```
+
+
**Info:** This assumes the `react-hooks` ESLint plugin is installed.
+
+
If using ESLint autofix, manually correct any `.value` additions to dependency arrays:
+
+
```javascript
+
const sv = useSharedValue(0)
+
+
// 🚨 bad: sv.value in array
+
const dv = useDerivedValue(() => sv.value, [sv.value])
+
+
// ✅ good: sv in array
+
const dv = useDerivedValue(() => sv.value, [sv])
+
```
+
+
### Solito / Next.js Compatibility
+
+
An experimental SWC plugin is being developed. Until then, follow the "Web without a Babel Plugin" instructions.
+
+
#### Next.js Polyfill
+
+
To use Reanimated with Next.js/Solito, add the `raf` polyfill for `requestAnimationFrame`:
+
+
```bash
+
yarn add raf
+
```
+
+
Include this at the top of your `_app.tsx`:
+
+
```javascript
+
import "raf/polyfill"
+
```
+
+
## runOnJS
+
+
The `runOnJS` function allows you to asynchronously execute functions that are not workletized on the UI thread. This is particularly useful for most external libraries, as their functions typically lack the `"worklet"` directive.
+
+
`runOnJS` is commonly used to update React state either after an animation completes or conditionally within a gesture interaction.
+
+
### Reference
+
+
```typescript
+
import { runOnJS } from "react-native-reanimated"
+
+
function App() {
+
// Executing on the UI thread
+
runOnJS(navigation.goBack)()
+
}
+
```
+
+
#### Arguments
+
+
##### `fn`
+
+
A reference to a function you wish to execute on the JavaScript thread from the UI thread. Any arguments for your function must be passed to the function returned by `runOnJS`, e.g., `runOnJS(setValue)(10);`.
+
+
#### Returns
+
+
`runOnJS` returns a function that accepts arguments for the original function provided as its first argument. This returned function can be safely executed on the UI thread.
+
+
**Note:** Ensure you call the function returned from `runOnJS`.
+
+
### Example
+
+
### Remarks
+
+
- Functions passed to `runOnJS` must be defined within the JavaScript thread scope, such as in a component body or global scope. The following code will not work because `myFunction` is defined inside the `withTiming` callback, which runs on the UI thread:
+
+
```typescript
+
withTiming(0, {}, () => {
+
// myFunction is defined on the UI thread 🚨
+
const myFunction = () => {
+
// ...
+
}
+
runOnJS(myFunction)() // 💥
+
})
+
```
+
+
- A common mistake is to execute a function inside `runOnJS` like this: ~~`runOnJS(setValue(10))()`~~. The correct usage would be `runOnJS(setValue)(10)`.
+
+
- It's safe to run functions via `runOnJS` on the JavaScript thread, as it has no adverse effects.
+
+
### Platform Compatibility
+
+
|Android|iOS|Web|
+
|-|-|-|
+
|✅|✅|✅|
+
+
## withTiming
+
+
`withTiming` enables you to create animations based on duration and easing functions.
+
+
### Reference
+
+
```typescript
+
import { withTiming } from "react-native-reanimated"
+
+
function App() {
+
sv.value = withTiming(0)
+
// ...
+
}
+
```
+
+
#### Arguments
+
+
##### `toValue`
+
+
The target value for the animation. Supported categories include:
+
+
- **Numbers**: Can be a number or a string representation of a number.
+
- **Suffixed Numbers**: Strings that combine numbers and units (e.g., `"5.5%"`, `"90deg"`, `"3bananas"`). Ensure no space between the number and suffix, with the suffix containing only basic English letters.
+
- **Colors**:
+
- Hexadecimal integer: e.g., `0xff1234`
+
- RGB: e.g., `"rgb(100, 50, 0)"`
+
- RGBA: e.g., `"rgba(255, 105, 180, 0.5)"`
+
- RGB Hexadecimal: e.g., `"#53575E"`
+
- HSL: e.g., `"hsl(0, 50%, 50%)"`
+
- Named colors: e.g., `"dodgerblue"`
+
- **Objects**: Objects with properties that will be animated individually.
+
- **Arrays**: Arrays of numbers where each value is animated separately.
+
- **Transformation Matrix**: An array of exactly 16 numerical values treated as a transformation matrix, decomposed into rotation, scale, and translation for animation.
+
+
Ensure `toValue` and the shared value being animated are of the same category (e.g., you cannot animate `width` from `100px` to `50%`).
+
+
##### `config` (Optional)
+
+
The configuration for timing animations. Available properties:
+
+
|Name|Type|Default|Description|
+
|-|-|-|-|
+
|duration|`number`|300|Length of the animation in milliseconds.|
+
|easing|`Easing`|`Easing.inOut(Easing.quad)`|An easing function defining the animation curve.|
+
|reduceMotion|`ReduceMotion`|`ReduceMotion.System`|Determines how the animation responds to reduced motion settings on devices.|
+
+
###### `Easing`
+
+
The `easing` parameter allows fine-tuning of the animation over time, such as starting with fast acceleration and slowing down towards the end.
+
+
Reanimated provides various easing functions in the `Easing` module. You can visualize common easing functions at [easings.net](http://easings.net/).
+
+
Use built-in easings by passing them to the `withTiming` config:
+
+
```typescript
+
import { Easing } from "react-native-reanimated"
+
+
withTiming(sv.value, {
+
easing: Easing.bounce,
+
})
+
```
+
+
Available functions include:
+
+
- `back`: Animation where the object slightly moves back before moving forward.
+
- `bezier(x1: number, y1: number, x2: number, y2: number)`: Cubic bezier curve.
+
- `bounce`: Bouncing animation.
+
- `circle`: Circular function.
+
- `cubic`: Cubic function.
+
- `ease`: Simple inertial animation.
+
- `elastic(bounciness?: number)`: Spring interaction.
+
- `exp`: Exponential function.
+
- `linear`: Linear function.
+
- `poly(n: number)`: Higher power functions like quartic, quintic.
+
- `quad`: Quadratic function.
+
- `sin`: Sinusoidal function.
+
+
Helpers to modify easing functions:
+
+
- `in(easing: EasingFunction)`: Runs an easing function forwards.
+
- `inOut(easing: EasingFunction)`: Symmetrical easing function.
+
- `out(easing: EasingFunction)`: Runs an easing function backwards.
+
+
##### `callback` (Optional)
+
+
A function called upon animation completion. If the animation is canceled, it receives `false`; otherwise, it receives `true`.
+
+
#### Returns
+
+
`withTiming` returns an animation object representing the current state of the animation. It can be assigned to a shared value or used in a style object from `useAnimatedStyle`.
+
+
### Example
+
+
### Remarks
+
+
- The callback passed as the third argument is automatically workletized and executed on the UI thread.
+
+
### Platform Compatibility
+
+
|Android|iOS|Web|
+
|-|-|-|
+
|✅|✅|✅|
+
+
## Animating styles and props
In this section, we explore different methods for passing animation styles to components. We will differentiate between animating styles and props using `useAnimatedStyle` and `useAnimatedProps`.
···
|-|-|-|
|✅|✅|✅|
-
## Run On JS
-
-
The `runOnJS` function allows you to asynchronously execute functions that are not workletized on the UI thread. This is particularly useful for most external libraries, as their functions typically lack the `"worklet"` directive.
+
## runOnUI
-
`runOnJS` is commonly used to update React state either after an animation completes or conditionally within a gesture interaction.
+
The `runOnUI` function allows you to asynchronously execute workletized functions on the UI thread. It is commonly used within an `useEffect` for initiating animations upon component mount or unmount, as well as with `measure` and `scrollTo` functions that are implemented solely on the UI thread.
### Reference
```typescript
-
import { runOnJS } from "react-native-reanimated"
+
import { runOnUI } from "react-native-reanimated"
function App() {
-
// Executing on the UI thread
-
runOnJS(navigation.goBack)()
+
// Example usage in an event handler or effect
+
runOnUI((greeting: string) => {
+
console.log(`${greeting} from the UI thread`)
+
})("Howdy")
+
+
// ...
```
#### Arguments
-
##### `fn`
+
##### fn
-
A reference to a function you wish to execute on the JavaScript thread from the UI thread. Any arguments for your function must be passed to the function returned by `runOnJS`, e.g., `runOnJS(setValue)(10);`.
+
A reference to a function intended for execution on the UI thread, originating from the JavaScript thread. Any arguments required by your function must be passed to the function returned by `runOnUI`, e.g., `runOnUI(myWorklet)(10)`.
#### Returns
-
`runOnJS` returns a function that accepts arguments for the original function provided as its first argument. This returned function can be safely executed on the UI thread.
+
`runOnUI` returns a function that accepts arguments for the initially provided function.
-
**Note:** Ensure you call the function returned from `runOnJS`.
+
**Note:** Ensure you invoke the function returned from `runOnUI`.
### Example
### Remarks
-
- Functions passed to `runOnJS` must be defined within the JavaScript thread scope, such as in a component body or global scope. The following code will not work because `myFunction` is defined inside the `withTiming` callback, which runs on the UI thread:
+
- When creating animations, prioritize more general solutions such as `useDerivedValue`, `useAnimatedReaction`, or executing code within gesture callbacks. Resort to using `runOnUI` only after exploring these alternatives.
-
```typescript
-
withTiming(0, {}, () => {
-
// myFunction is defined on the UI thread 🚨
-
const myFunction = () => {
-
// ...
-
}
-
runOnJS(myFunction)() // 💥
-
})
-
```
+
- A common error is attempting to execute a function inside of `runOnUI` like this: ~~`runOnUI(myWorklet(10))()`~~. The correct usage should be `runOnUI(myWorklet)(10)`.
-
- A common mistake is to execute a function inside `runOnJS` like this: ~~`runOnJS(setValue(10))()`~~. The correct usage would be `runOnJS(setValue)(10)`.
+
- The callback provided as an argument is automatically workletized, making it ready for execution on the UI thread.
-
- It's safe to run functions via `runOnJS` on the JavaScript thread, as it has no adverse effects.
+
- Avoid executing `runOnUI` directly on the UI thread to prevent errors.
### Platform Compatibility
···
|-|-|-|
|✅|✅|✅|
-
## runOnUI
+
## runOnRuntime
-
The `runOnUI` function allows you to asynchronously execute workletized functions on the UI thread. It is commonly used within an `useEffect` for initiating animations upon component mount or unmount, as well as with `measure` and `scrollTo` functions that are implemented solely on the UI thread.
+
The `runOnRuntime` function allows you to execute workletized functions asynchronously on a separate worklet runtime, which operates on a different thread.
### Reference
```typescript
-
import { runOnUI } from "react-native-reanimated"
+
import { createWorkletRuntime, runOnRuntime } from "react-native-reanimated"
+
+
const workletRuntime = createWorkletRuntime("background")
function App() {
// Example usage in an event handler or effect
-
runOnUI((greeting: string) => {
-
console.log(`${greeting} from the UI thread`)
+
runOnRuntime(workletRuntime, (greeting) => {
+
console.log(`${greeting} from a separate thread`)
})("Howdy")
// ...
···
```
#### Arguments
+
+
##### workletRuntime
+
+
A reference to the worklet runtime created using `createWorkletRuntime`.
##### fn
-
A reference to a function intended for execution on the UI thread, originating from the JavaScript thread. Any arguments required by your function must be passed to the function returned by `runOnUI`, e.g., `runOnUI(myWorklet)(10)`.
+
A function intended for execution on the UI thread from the JavaScript thread. The arguments for this function must be passed to the function returned by `runOnUI`, e.g., `runOnUI(myWorklet)(10)`.
#### Returns
-
`runOnUI` returns a function that accepts arguments for the initially provided function.
-
-
**Note:** Ensure you invoke the function returned from `runOnUI`.
+
`runOnRuntime` returns a function that accepts arguments for the function provided as its first argument.
-
### Example
+
**Note:** Ensure you call the function returned from `runOnRuntime`.
### Remarks
-
- When creating animations, prioritize more general solutions such as `useDerivedValue`, `useAnimatedReaction`, or executing code within gesture callbacks. Resort to using `runOnUI` only after exploring these alternatives.
+
- A common mistake is to execute a function inside of `runOnRuntime` incorrectly, such as: ~~`runOnRuntime(myWorklet(10))()`~~. The correct usage is `runOnRuntime(myWorklet)(10)`.
-
- A common error is attempting to execute a function inside of `runOnUI` like this: ~~`runOnUI(myWorklet(10))()`~~. The correct usage should be `runOnUI(myWorklet)(10)`.
+
- The callback passed as an argument will not be automatically workletized. You must manually add the `'worklet';` directive to enable execution on the UI thread.
-
- The callback provided as an argument is automatically workletized, making it ready for execution on the UI thread.
+
- `runOnRuntime` can be called on any runtime, including the RN runtime, UI runtime, and other worklet runtimes.
-
- Avoid executing `runOnUI` directly on the UI thread to prevent errors.
+
- The function provided to `runOnRuntime` is added to an execution queue on a separate thread and executed asynchronously on the specified worklet runtime. Functions are executed in the order they were queued.
### Platform Compatibility
|Android|iOS|Web|
|-|-|-|
-
|✅|✅|✅|
+
|✅|✅|❌|
-
## Your First Animation
+
## Applying modifiers
-
This section introduces you to the basics of Reanimated. If you're new to this library, you'll find guidance on creating a simple animation that lays the foundation for more advanced skills.
+
Reanimated provides built-in modifiers for customizing animations: `withRepeat`, `withSequence`, and `withDelay`. This guide demonstrates how to use these modifiers by creating a shake animation.
-
### Using an Animated Component
+
### Starting Point
-
To start animating components in React Native using Reanimated, import the `Animated` object:
+
We'll create an animated box that shakes on button press after a delay. The setup involves using `useAnimatedStyle` and the `withTiming` function to move the box 40px to the right smoothly.
```typescript
-
import Animated from "react-native-reanimated"
-
```
+
export default function App() {
+
const offset = useSharedValue<number>(0);
-
The `Animated` object wraps native components like `View`, `ScrollView`, or `FlatList`. Use these components as you would any other JSX component:
+
const style = useAnimatedStyle(() => ({
+
transform: [{ translateX: offset.value }],
+
}));
-
```typescript
-
import Animated from 'react-native-reanimated';
+
const OFFSET = 40;
-
export default function App() {
+
const handlePress = () => {
+
offset.value = withTiming(OFFSET);
+
};
+
return (
-
<Animated.View
-
style={{
-
width: 100,
-
height: 100,
-
backgroundColor: 'violet',
-
}}
-
/>
+
<View style={styles.container}>
+
<Animated.View style={[styles.box, style]} />
+
<Button title="shake" onPress={handlePress} />
+
</View>
);
```
-
### Defining a Shared Value
+
### Repeating an Animation
-
Shared values are essential for animations, acting like React state synchronized between JavaScript and the native side. Create shared values using `useSharedValue`:
+
To create a shake effect, use the `withRepeat` modifier. This allows you to repeat an animation multiple times or indefinitely.
```typescript
-
import { useSharedValue } from "react-native-reanimated"
+
import { withRepeat } from "react-native-reanimated"
+
+
function App() {
+
sv.value = withRepeat(withTiming(50), 5)
+
}
```
-
Define shared values within your component's body to store any JS value or data structure.
+
Pass a number for repetitions or a non-positive value for infinite repetition. Use `true` as the third argument to reverse the animation direction.
-
For example, set a default value of `100` for width in an `Animated.View`:
+
Updated example:
```typescript
-
import Animated, { useSharedValue } from 'react-native-reanimated';
+
export default function App() {
+
const offset = useSharedValue<number>(0);
+
+
const style = useAnimatedStyle(() => ({
+
transform: [{ translateX: offset.value }],
+
}));
+
+
const OFFSET = 40;
-
export default function App() {
-
const width = useSharedValue(100);
+
const handlePress = () => {
+
offset.value = withRepeat(withTiming(OFFSET), 5, true);
+
};
return (
-
<Animated.View
-
style={{
-
width,
-
height: 100,
-
backgroundColor: 'violet',
-
}}
-
/>
+
<View style={styles.container}>
+
<Animated.View style={[styles.box, style]} />
+
<Button title="shake" onPress={handlePress} />
+
</View>
);
```
-
### Using a Shared Value
-
-
Create an animation that modifies the `width` of an element by `50px` on each button press. Modify the shared value connected to the `Animated.View`'s width property.
+
### Running Animations in a Sequence
-
Access and modify values stored in shared values using their `.value` property:
+
To enhance the animation, use `withSequence` to chain animations. This modifier starts the next animation when the previous one ends.
```typescript
-
import { Button, View } from 'react-native';
-
import Animated, { useSharedValue } from 'react-native-reanimated';
+
import { withSequence } from "react-native-reanimated"
-
export default function App() {
-
const width = useSharedValue(100);
+
function App() {
+
sv.value = withSequence(withTiming(50), withTiming(0))
+
}
+
```
-
const handlePress = () => {
-
width.value = width.value + 50;
-
};
+
Improved example:
-
return (
-
<View style={{ flex: 1, alignItems: 'center' }}>
-
<Animated.View
-
style={{
-
width,
-
height: 100,
-
backgroundColor: 'violet',
-
}}
-
/>
-
<Button onPress={handlePress} title="Click me" />
-
</View>
-
);
+
```typescript
+
const TIME = 250
+
+
const handlePress = () => {
+
offset.value = withSequence(
+
// start from -OFFSET
+
withTiming(-OFFSET, { duration: TIME / 2 }),
+
// shake between -OFFSET and OFFSET 5 times
+
withRepeat(withTiming(OFFSET, { duration: TIME }), 5, true),
+
// go back to 0 at the end
+
withTiming(0, { duration: TIME / 2 })
+
)
```
-
Avoid directly modifying shared values without using the `.value` property, as in `sv.value = sv.value + 100`.
-
-
### Using an Animation Function
+
### Starting the Animation with Delay
-
To animate smoothly, import and use the `withSpring` function. Wrap it around the new width value to create a spring animation:
+
Add suspense by delaying the animation start using `withDelay`.
```typescript
-
import { Button, View } from 'react-native';
-
import Animated, { useSharedValue, withSpring } from 'react-native-reanimated';
+
import { withDelay } from "react-native-reanimated"
+
+
function App() {
+
sv.value = withDelay(500, withTiming(0))
+
}
+
```
-
export default function App() {
-
const width = useSharedValue(100);
+
Final example:
-
const handlePress = () => {
-
width.value = withSpring(width.value + 50);
-
};
+
```typescript
+
const OFFSET = 40
+
const TIME = 250
+
const DELAY = 400
-
return (
-
<View style={{ flex: 1, alignItems: 'center' }}>
-
<Animated.View
-
style={{
-
width,
-
height: 100,
-
backgroundColor: 'violet',
-
}}
-
/>
-
<Button onPress={handlePress} title="Click me" />
-
</View>
-
);
+
const handlePress = () => {
+
offset.value = withDelay(
+
DELAY,
+
withSequence(
+
// start from -OFFSET
+
withTiming(-OFFSET, { duration: TIME / 2 }),
+
// shake between -OFFSET and OFFSET 5 times
+
withRepeat(withTiming(OFFSET, { duration: TIME }), 5, true),
+
// go back to 0 at the end
+
withTiming(0, { duration: TIME / 2 })
+
)
+
)
```
-
This creates a bouncy spring animation for the element's width.
-
### Summary
-
In this section, you learned about:
-
-
- `Animated` components to define animatable elements.
-
- Shared values as the driving factor of animations using `useSharedValue`.
-
- Accessing and modifying shared values via their `.value` property (e.g., `sv.value = 100;`).
-
- Creating smooth animations by modifying shared values with functions like `withSpring`.
+
- **Modifiers**: `withRepeat`, `withSequence`, and `withDelay`.
+
- **`withRepeat`**: Repeats an animation a specified number of times or indefinitely.
+
- **`withSequence`**: Chains animations to run sequentially.
+
- **`withDelay`**: Delays the start of an animation.
### What's Next?
-
In the next section, you'll explore animating styles and props using `useAnimatedStyle` and `useAnimatedProps` hooks.
+
Explore handling `Tap` and `Pan` gestures, and learn about the `withDecay` animation function.
## withDecay
···
|-|-|-|
|✅|✅|✅|
-
## runOnRuntime
+
## createWorkletRuntime
-
The `runOnRuntime` function allows you to execute workletized functions asynchronously on a separate worklet runtime, which operates on a different thread.
+
The `createWorkletRuntime` function allows for the creation of a new JavaScript runtime that can execute worklets on threads separate from the main JavaScript or UI thread. This functionality is intended primarily for use by third-party libraries integrating with worklets. The returned value represents this runtime and should be communicated to the C++ side via JSI (JavaScript Interface) for further operations.
### Reference
+
+
#### Usage in JavaScript
```typescript
-
import { createWorkletRuntime, runOnRuntime } from "react-native-reanimated"
-
-
const workletRuntime = createWorkletRuntime("background")
+
import { createWorkletRuntime } from "react-native-reanimated"
function App() {
-
// Example usage in an event handler or effect
-
runOnRuntime(workletRuntime, (greeting) => {
-
console.log(`${greeting} from a separate thread`)
-
})("Howdy")
-
-
// ...
+
const runtime = createWorkletRuntime("background")
```
-
#### Arguments
+
#### Usage in C++
-
##### workletRuntime
+
```cpp
+
auto runtime = reanimated::extractWorkletRuntime(rt, runtimeValue);
-
A reference to the worklet runtime created using `createWorkletRuntime`.
+
jsi::Runtime &rt = runtime->getJSIRuntime();
-
##### fn
+
auto worklet = reanimated::extractShareableOrThrow<reanimated::ShareableWorklet>(rt, workletValue);
-
A function intended for execution on the UI thread from the JavaScript thread. The arguments for this function must be passed to the function returned by `runOnUI`, e.g., `runOnUI(myWorklet)(10)`.
+
runtime->runGuarded(worklet, ...args);
+
```
-
#### Returns
+
#### Arguments
-
`runOnRuntime` returns a function that accepts arguments for the function provided as its first argument.
+
- **`name`**: A string identifier for the runtime that will appear in device lists within Chrome DevTools.
-
**Note:** Ensure you call the function returned from `runOnRuntime`.
+
- **`initializer`** (optional): A worklet executed synchronously on the same thread immediately after the runtime's creation. This can be used to inject global variables or functions into the runtime.
+
+
#### Returns
+
+
The `createWorkletRuntime` function returns a `WorkletRuntime`, which is represented as a `jsi::HostObject<reanimated::WorkletRuntime>`.
### Remarks
-
- A common mistake is to execute a function inside of `runOnRuntime` incorrectly, such as: ~~`runOnRuntime(myWorklet(10))()`~~. The correct usage is `runOnRuntime(myWorklet)(10)`.
+
- Worklet runtimes include built-in support for `performance.now` and `console.*` methods. Other APIs are not available by default and must be injected or captured via worklet closures.
-
- The callback passed as an argument will not be automatically workletized. You must manually add the `'worklet';` directive to enable execution on the UI thread.
+
- In development mode, unhandled errors thrown within the runtime (excluding those in the `initializer`) will be caught, logged to the console, and displayed in a LogBox.
-
- `runOnRuntime` can be called on any runtime, including the RN runtime, UI runtime, and other worklet runtimes.
+
- Chrome DevTools can be used for debugging the runtime when using Hermes. The runtime appears in the devices list as specified by the `name` argument passed to `createWorkletRuntime`.
-
- The function provided to `runOnRuntime` is added to an execution queue on a separate thread and executed asynchronously on the specified worklet runtime. Functions are executed in the order they were queued.
+
- Shared values have limited support within worklet runtimes. To write to a shared value from the React Native (RN) runtime and read it on the worklet runtime, use `runOnRuntime`. Otherwise, updates will only reflect in the RN and UI runtimes.
### Platform Compatibility
···
|-|-|-|
|✅|✅|❌|
-
## Canceling Animations with `cancelAnimation`
+
## interpolate
+
+
The `interpolate` function is used to map a numeric value from one specified range to another using linear interpolation.
+
+
### Reference Usage
+
+
```typescript
+
import { interpolate, Extrapolation } from "react-native-reanimated"
+
+
function App() {
+
const animatedStyle = useAnimatedStyle(() => ({
+
opacity: interpolate(sv.value, [0, 100], [0, 1], Extrapolation.CLAMP),
+
}))
+
}
+
```
+
+
#### Parameters
+
+
- **`value`**: A numeric value that will be mapped to the specified `output` range.
+
+
- **`input`**: An array of numbers defining the input range for interpolation.
+
+
- **`output`**: An array of numbers defining the output range for interpolation, which should have at least as many points as the input range.
+
+
- **`extrapolate` (Optional)**: Determines behavior when `value` is outside the `input` range. Defaults to `Extrapolation.EXTEND`.
+
+
Available options:
+
+
- `Extrapolation.EXTEND`: Predicts values beyond the output range.
+
- `Extrapolation.CLAMP`: Clamps the value to the edge of the output range.
+
- `Extrapolation.IDENTITY`: Returns the provided value unchanged.
+
+
String equivalents include `"extend"`, `"clamp"`, and `"identity"`.
+
+
To apply extrapolation to a specific edge, use an object:
+
+
```typescript
+
const opacity = interpolate(sv.value, [0, 100], [0, 1], {
+
extrapolateLeft: Extrapolation.CLAMP,
+
})
+
```
+
+
#### Return Value
+
+
The `interpolate` function returns a value mapped within the specified output range.
+
+
### Platform Compatibility
+
+
|Android|iOS|Web|
+
|-|-|-|
+
|✅|✅|✅|
+
+
## cancelAnimation
The `cancelAnimation` function is used to stop an ongoing animation associated with a shared value in React Native Reanimated.
···
This function is compatible across Android, iOS, and web platforms.
-
## createWorkletRuntime
+
## Clamp Function in React Native Reanimated
-
The `createWorkletRuntime` function allows for the creation of a new JavaScript runtime that can execute worklets on threads separate from the main JavaScript or UI thread. This functionality is intended primarily for use by third-party libraries integrating with worklets. The returned value represents this runtime and should be communicated to the C++ side via JSI (JavaScript Interface) for further operations.
+
The `clamp` function is used to restrict a value within a specified range, ensuring it does not exceed the defined minimum and maximum bounds.
### Reference
-
#### Usage in JavaScript
+
```typescript
+
import { clamp } from "react-native-reanimated"
+
+
function App() {
+
const result = clamp(sv.value, 0, 100)
+
}
+
```
+
+
#### Arguments
+
+
- **`value`**: A numeric value that will be returned if it falls within the specified `min` and `max` range.
+
+
- **`min`**: The lower bound. If the provided `value` is less than this number, `min` will be returned.
+
+
- **`max`**: The upper bound. If the provided `value` exceeds this number, `max` will be returned.
+
+
#### Returns
+
+
The function returns a numeric value that lies between the specified `min` and `max` bounds.
+
+
### Example Usage
```typescript
-
import { createWorkletRuntime } from "react-native-reanimated"
+
import { clamp } from "react-native-reanimated"
function App() {
-
const runtime = createWorkletRuntime("background")
+
const constrainedValue = clamp(150, 0, 100) // Result will be 100
```
-
#### Usage in C++
+
### Platform Compatibility
-
```cpp
-
auto runtime = reanimated::extractWorkletRuntime(rt, runtimeValue);
+
|Android|iOS|Web|
+
|-|-|-|
+
|✅|✅|✅|
+
+
This function is compatible across Android, iOS, and Web platforms.
+
+
## interpolateColor
+
+
The `interpolateColor` function maps an input range to output colors using linear interpolation. This is particularly useful in animations where you want a smooth transition between colors.
+
+
### Reference Example
+
+
```typescript
+
import { interpolateColor } from 'react-native-reanimated';
+
+
function App() {
+
const progress = useSharedValue(0);
-
jsi::Runtime &rt = runtime->getJSIRuntime();
+
const animatedStyle = useAnimatedStyle(() => {
+
return {
+
backgroundColor: interpolateColor(
+
progress.value,
+
[0, 1],
+
['red', 'green']
+
),
+
};
+
});
-
auto worklet = reanimated::extractShareableOrThrow<reanimated::ShareableWorklet>(rt, workletValue);
+
// ...
-
runtime->runGuarded(worklet, ...args);
+
return <Animated.View style={[{ width: 100, height: 100 }, animatedStyle]} />;
+
}
```
#### Arguments
-
- **`name`**: A string identifier for the runtime that will appear in device lists within Chrome DevTools.
+
- **`value`**: A number from the input range that is mapped to the output range.
+
+
- **`input`**: An array of numbers specifying the input range for interpolation. The values should be in increasing order.
+
+
- **`output`**: An array of color strings (e.g., `'red'`, `'#ff0000'`, `'rgba(255, 0, 0, 0.5)'`) that define the output colors. It must have at least as many points as the input range.
-
- **`initializer`** (optional): A worklet executed synchronously on the same thread immediately after the runtime's creation. This can be used to inject global variables or functions into the runtime.
+
- **`colorSpace`** *(Optional)*: Specifies the color space for interpolation, either `'HSV'` or `'RGB'`. Defaults to `'RGB'`.
+
+
- **`options`** *(Optional)*: Additional parameters for color interpolation:
+
+
|Options|Type|Default|Description|
+
|-|-|-|-|
+
|`gamma`|`number`|2.2|Gamma parameter used in gamma correction.|
+
|`useCorrectedHSVInterpolation`|`boolean`|true|Reduces the number of hues during interpolation by treating HSV as circular.|
+
+
#### Options Explanation
+
+
- **Gamma**: Colors on web/mobile are typically expressed in sRGB, a gamma-corrected color space. Operations like addition can yield incorrect results if performed directly in this non-linear space. To address this, colors are converted to linear space for interpolation and then back to sRGB. The default gamma value of 2.2 is commonly used for this conversion.
+
+
- **Use Corrected HSV Interpolation**: This option optimizes hue transitions by selecting the shortest path on a circular spectrum (e.g., transitioning from yellow to purple via red instead of green and blue).
#### Returns
-
The `createWorkletRuntime` function returns a `WorkletRuntime`, which is represented as a `jsi::HostObject<reanimated::WorkletRuntime>`.
+
The function returns an interpolated color in `rgba(r, g, b, a)` format within the specified output range.
### Remarks
-
- Worklet runtimes include built-in support for `performance.now` and `console.*` methods. Other APIs are not available by default and must be injected or captured via worklet closures.
+
- The function operates similarly to the `interpolate` function but specifically outputs a color string in `rgba(r, g, b, a)` notation.
+
+
### Platform Compatibility
+
+
|Android|iOS|Web|
+
|-|-|-|
+
|✅|✅|✅|
+
+
This function is versatile and compatible across major platforms, making it ideal for cross-platform applications.
+
+
## withSequence
+
+
`withSequence` is an animation modifier that allows animations to be executed in a sequential order.
+
+
### Reference
+
+
```typescript
+
import { withSequence } from "react-native-reanimated"
+
+
function App() {
+
sv.value = withSequence(withTiming(50), withTiming(0))
+
// ...
+
}
+
```
+
+
#### Arguments
+
+
##### `reduceMotion` (Optional)
+
+
A parameter that specifies how the animation should respond to the device's reduced motion accessibility setting.
+
+
##### `...animations`
+
+
Any number of animation objects that will be executed in sequence.
+
+
#### Returns
+
+
The `withSequence` function returns an animation object representing the current state of the animation. This object can either be directly assigned to a shared value or used as a value for a style object returned from `useAnimatedStyle`.
+
+
### Example
+
+
### Platform Compatibility
+
+
|Android|iOS|Web|
+
|-|-|-|
+
|✅|✅|✅|
-
- In development mode, unhandled errors thrown within the runtime (excluding those in the `initializer`) will be caught, logged to the console, and displayed in a LogBox.
+
## scrollTo
-
- Chrome DevTools can be used for debugging the runtime when using Hermes. The runtime appears in the devices list as specified by the `name` argument passed to `createWorkletRuntime`.
+
The `scrollTo` function allows you to synchronously scroll a component to a specified X or Y offset.
-
- Shared values have limited support within worklet runtimes. To write to a shared value from the React Native (RN) runtime and read it on the worklet runtime, use `runOnRuntime`. Otherwise, updates will only reflect in the RN and UI runtimes.
+
### Reference
+
+
```typescript
+
import { scrollTo } from 'react-native-reanimated';
+
+
function App() {
+
const animatedRef = useAnimatedRef();
+
const scrollY = useSharedValue(0);
+
+
useDerivedValue(() => {
+
scrollTo(animatedRef, 0, scrollY.value, true);
+
});
+
+
return (
+
<Animated.ScrollView ref={animatedRef}>{/* ... */}</Animated.ScrollView>
+
);
+
}
+
```
+
+
#### Arguments
+
+
- **`animatedRef`**: An animated reference linked to the ScrollView (or another scrollable) component you wish to scroll. This animated reference must be passed to either an Animated component or a React Native built-in component.
+
+
- **`x`**: The pixel value for horizontal scrolling on the X axis.
+
+
- **`y`**: The pixel value for vertical scrolling on the Y axis.
+
+
- **`animated`**: A boolean indicating if the scroll should be smooth (`true`) or instant (`false`).
+
+
#### Returns
+
+
The `scrollTo` function returns `undefined`.
+
+
### Remarks
+
+
- The `scrollTo` function must be invoked from the UI thread.
+
- It supports `Animated.FlatList`.
+
- Typically works with other ScrollView-like and FlatList-like components if they use a `ScrollView` internally and are animated.
+
- Scrollable components need to implement the `getScrollableNode` method (and `getNativeScrollRef` for New Architecture) to be compatible with `scrollTo`.
### Platform Compatibility
|Android|iOS|Web|
|-|-|-|
-
|✅|✅|❌|
+
|✅|✅|✅|
+
+
## getRelativeCoords Functionality
+
+
The `getRelativeCoords` function is used to determine the screen location relative to a specified view.
-
```markdown
-
# `useAnimatedGestureHandler`
+
### Reference Code
+
+
```typescript
+
import { getRelativeCoords } from 'react-native-reanimated';
-
**Note:** This API has been deprecated. It no longer receives updates and will be removed in a future major release of Reanimated.
+
const Comp = () => {
+
const animatedRef = useAnimatedRef();
-
## Overview
+
const gestureHandler = useAnimatedGestureHandler({
+
onEnd: (event) => {
+
const coords = getRelativeCoords(
+
animatedRef,
+
event.absoluteX,
+
event.absoluteY
+
);
+
},
+
});
-
The `useAnimatedGestureHandler` function is part of the Reanimated library, which provides tools for creating smooth animations on React Native applications. However, due to its deprecation status, developers are advised to seek alternative solutions or APIs that offer similar functionality but with ongoing support and updates.
+
return (
+
<View ref={animatedRef}>
+
<PanGestureHandler onGestureEvent={gestureHandler}>
+
<Animated.View style={[styles.box]} />
+
</PanGestureHandler>
+
</View>
+
);
+
};
```
-
## Applying Modifiers in Reanimated
+
### Arguments
+
+
- **`animatedRef`**: This is the result of `useAnimatedRef`, which extends a standard React ref to deliver the view tag on the UI thread. It should be passed as a prop to the view relative to which coordinates are needed.
+
+
- **`absoluteX`**: A number representing the absolute x-coordinate.
+
+
- **`absoluteY`**: A number representing the absolute y-coordinate.
-
Reanimated provides built-in modifiers for customizing animations: `withRepeat`, `withSequence`, and `withDelay`. This guide demonstrates how to use these modifiers by creating a shake animation.
+
### Returns
-
### Starting Point
+
An object containing:
-
We'll create an animated box that shakes on button press after a delay. The setup involves using `useAnimatedStyle` and the `withTiming` function to move the box 40px to the right smoothly.
+
- `x`: The relative x-coordinate.
+
- `y`: The relative y-coordinate.
+
+
### Platform Compatibility
+
+
|Android|iOS|Web|
+
|-|-|-|
+
|✅|✅|✅|
+
+
## useAnimatedGestureHandler
+
+
**Warning:**\
+
The `useAnimatedGestureHandler` hook allows for the creation of animations based on gesture handlers. It is essential to provide the object created by this hook to the `onGestureEvent` property of a gesture handler component.
+
+
This hook necessitates that `react-native-gesture-handler` be installed and configured within your project.
+
+
### Reference
+
+
```typescript
+
import { useAnimatedGestureHandler } from 'react-native-reanimated';
+
import { PanGestureHandler } from 'react-native-gesture-handler';
+
+
function App() {
+
const x = useSharedValue(0);
+
+
const gestureHandler = useAnimatedGestureHandler({
+
onStart: (_, ctx) => {
+
ctx.startX = x.value;
+
},
+
onActive: (event, ctx) => {
+
x.value = ctx.startX + event.translationX;
+
},
+
});
+
+
return (
+
<PanGestureHandler onGestureEvent={gestureHandler}>
+
<Animated.View />
+
</PanGestureHandler>
+
);
+
}
+
```
+
+
#### Arguments
+
+
##### `gestureHandlers`
+
+
The primary argument is an object that can include one or more handlers. These handlers are set under the following keys: `onStart`, `onActive`, `onEnd`, `onFail`, `onCancel`, and `onFinish`.
+
+
Each handler will be activated based on the current state of the associated gesture handler. For further details, refer to the Gesture Handler documentation. The handler receives:
+
+
- `event` \[object] - an event object containing the payload specific to the type of gesture handler (e.g., `PanGestureHandler`, `RotationGestureHandler`).
+
+
- `context` \[object] - a JavaScript object for storing state information. This context can be read and modified, persisting between events and across handlers for all selected states.
+
+
##### `dependencies` (Optional)
+
+
An optional array of dependencies is relevant only when using Reanimated without the Babel plugin on the Web.
+
+
#### Returns
+
+
The `useAnimatedGestureHandler` hook returns a handler object that can be attached to gesture handler components from the `react-native-gesture-handler` library. This object must be passed to the `onGestureEvent` property of a gesture handler component.
+
+
### Example
+
+
### Platform Compatibility
+
+
|Android|iOS|Web|
+
|-|-|-|
+
|✅|✅|⚠️|
+
+
- On the Web, it is necessary to pass the returned handler object to both `onGestureEvent` and `onHandlerStateChange` parameters.
+
+
## useScrollViewOffset Hook
+
+
The `useScrollViewOffset` hook enables the creation of animations based on a `ScrollView`'s offset. It automatically determines whether the `ScrollView` is oriented horizontally or vertically.
+
+
### Reference
+
+
```typescript
+
import { useAnimatedRef, useScrollViewOffset } from 'react-native-reanimated';
+
+
function App() {
+
const animatedRef = useAnimatedRef();
+
const scrollOffset = useScrollViewOffset(animatedRef);
+
+
return (
+
<Animated.ScrollView ref={animatedRef}>
+
{/* Content goes here */}
+
</Animated.ScrollView>
+
);
+
}
+
```
+
+
#### Arguments
+
+
##### `animatedRef`
+
+
An animated reference linked to the `ScrollView` component you wish to monitor. This animated reference must be assigned either to an Animated component or a React Native built-in component.
+
+
##### `initialRef` (Optional)
+
+
A shared value that can optionally be updated with the scroll offset. If not provided, a new shared value will be created internally by default.
+
+
#### Returns
+
+
The hook returns a shared value representing the current offset of the `ScrollView`.
+
+
### Example Usage
+
+
- The `animatedRef` argument can be dynamically changed, and the hook will continue to provide accurate values based on the connected `ScrollView`. For instance:
+
+
```typescript
+
useScrollViewOffset(someState ? someScrollRefA : someScrollRefB)
+
```
+
+
### Platform Compatibility
+
+
|Android|iOS|Web|
+
|-|-|-|
+
|✅|✅|✅|
+
+
## measure
+
+
The `measure` function allows you to synchronously obtain the dimensions and position of a view on the screen, executed on the UI thread.
+
+
### Reference
+
+
```typescript
+
import { measure } from 'react-native-reanimated';
+
+
function App() {
+
const animatedRef = useAnimatedRef();
+
+
const handlePress = () => {
+
runOnUI(() => {
+
const measurement = measure(animatedRef);
+
if (measurement === null) {
+
return;
+
}
+
// Additional logic can be added here
+
})();
+
};
+
+
return <Animated.View ref={animatedRef} />;
+
}
+
```
+
+
#### Arguments
+
+
- **`animatedRef`**: An animated reference linked to the component whose measurements are desired. This reference must be associated with either an Animated component or a React Native built-in component.
+
+
#### Returns
+
+
The `measure` function returns an object containing:
+
+
|Field|Description|
+
|-|-|
+
|`x`|A number representing the X coordinate relative to the parent component.|
+
|`y`|A number representing the Y coordinate relative to the parent component.|
+
|`width`|A number representing the width of the component.|
+
|`height`|A number representing the height of the component.|
+
|`pageX`|A number representing the X coordinate relative to the screen.|
+
|`pageY`|A number representing the Y coordinate relative to the screen.|
+
+
Alternatively, it returns `null` if the measurement could not be performed.
+
+
### Remarks
+
+
- **UI Thread Execution**: The `measure` function operates exclusively on the UI thread. When used within event handlers, it must be wrapped with the `runOnUI` function.
+
+
- **Use in `useAnimatedStyle`**: Since `useAnimatedStyle` is initially evaluated on the JavaScript thread before views are attached to the native side, a condition like the following should be included:
+
+
```typescript
+
function App() {
+
const animatedStyles = useAnimatedStyle(() => {
+
if (_WORKLET) {
+
// Safely use measure here
+
const measurement = measure(animatedRef)
+
}
+
})
+
}
+
```
+
+
- **Consecutive Runs**: Subsequent executions of `useAnimatedStyle` occur on the UI thread.
+
+
- **Alternative for Static Dimensions**: If only static dimensions are needed and measurements aren't used during animations, consider using the `onLayout` property instead.
+
+
- **Null Check**: It's advisable to check if the measurement result is `null`, as it may happen when the reference hasn't yet attached to a view:
+
+
```typescript
+
const animatedRef = useAnimatedRef()
+
+
const handlePress = () => {
+
runOnUI(() => {
+
const measurement = measure(animatedRef)
+
+
if (measurement === null) {
+
return
+
}
+
// Additional logic can be added here
+
})()
+
}
+
```
+
+
- **Rendered Components Only**: `measure` is applicable only to rendered components. For example, measuring off-screen items in a `FlatList` will yield `null`.
+
+
- **Debugger Compatibility**: The `measure` function isn't available with the Remote JS Debugger. It's recommended to use Chrome DevTools (`chrome://inspect`) for debugging React Native applications.
+
+
### Platform Compatibility
+
+
|Android|iOS|Web|
+
|-|-|-|
+
|✅|✅|✅|
+
+
## useAnimatedReaction
+
+
The `useAnimatedReaction` hook enables responses to changes in shared values, particularly useful when comparing previous and current values stored within a shared value.
+
+
### Reference
+
+
```typescript
+
import { useAnimatedReaction } from "react-native-reanimated"
+
+
function App() {
+
useAnimatedReaction(
+
() => sv.value,
+
(currentValue, previousValue) => {
+
if (currentValue !== previousValue) {
+
// perform an action ✨
+
}
+
}
+
)
+
+
// ...
+
}
+
```
+
+
#### Arguments
+
+
##### `prepare`
+
+
A function returning the value to which you want to react. This returned value serves as the first parameter for the `react` argument.
+
+
```typescript
+
function App() {
+
useAnimatedReaction(
+
() => Math.floor(sv.value),
+
(currentValue, previousValue) => {
+
// ...
+
}
+
)
+
}
+
```
+
+
##### `react`
+
+
A function that responds to changes in the value provided by the `prepare` function. It receives two parameters: the current value from `prepare` and the previous value, initially set to `null`.
+
+
```typescript
+
function App() {
+
useAnimatedReaction(
+
() => Math.floor(sv.value),
+
(currentValue, previousValue) => {
+
// ...
+
}
+
)
+
}
+
```
+
+
##### `dependencies` (Optional)
+
+
An optional array of dependencies. This is only relevant when using Reanimated without the Babel plugin on the Web.
+
+
#### Returns
+
+
The `useAnimatedReaction` hook returns `undefined`.
+
+
### Example
+
+
### Remarks
+
+
- Avoid mutating the same shared value in the `react` function that was used in the `prepare` function to prevent infinite loops.
+
+
```typescript
+
function App() {
+
useAnimatedReaction(
+
() => width.value,
+
(currentValue) => {
+
// 🚨 An infinite loop!
+
width.value += currentValue
+
}
+
)
+
}
+
```
+
+
- Callbacks for both `prepare` and `react` are automatically workletized, running on the UI thread.
+
+
- While you can use `useAnimatedReaction` to react to any stateful React value, it's generally better to use a `useEffect` for such purposes.
+
+
### Platform Compatibility
+
+
|Android|iOS|Web|
+
|-|-|-|
+
|✅|✅|✅|
+
+
## Animating styles and props
+
+
In this section, we explore different methods for passing animation styles to components. We will differentiate between animating styles and props using `useAnimatedStyle` and `useAnimatedProps`.
+
+
### Animating Styles
+
+
Previously, we learned about simple animations and shared values. While inline styling works well in basic cases, it has limitations, such as not allowing access to the value stored in a shared value for complex operations.
+
+
```typescript
+
import Animated, { useSharedValue } from 'react-native-reanimated';
+
+
function App() {
+
const width = useSharedValue(100);
+
+
return <Animated.View style={{ width }} />;
+
}
+
```
+
+
For example, multiplying a shared value before assigning it to the `style` prop is not possible:
+
+
```typescript
+
<Animated.View style={{ width: width * 5 }} /> // This won't work
+
```
+
+
Consider an example where a box moves right on button press:
+
+
```typescript
+
import { View, Button } from 'react-native';
+
import Animated, { useSharedValue, withSpring } from 'react-native-reanimated';
+
+
function App() {
+
const translateX = useSharedValue(0);
+
+
const handlePress = () => {
+
translateX.value = withSpring(translateX.value + 50);
+
};
+
+
return (
+
<View style={styles.container}>
+
<Animated.View style={[styles.box, { transform: [{ translateX }] }]} />
+
<Button onPress={handlePress} title="Click me" />
+
</View>
+
);
+
}
+
```
+
+
To customize shared value changes based on user input, `useAnimatedStyle` is used for more control and flexibility:
```typescript
export default function App() {
-
const offset = useSharedValue<number>(0);
+
const translateX = useSharedValue<number>(0);
+
+
const handlePress = () => {
+
translateX.value += 50;
+
};
-
const style = useAnimatedStyle(() => ({
-
transform: [{ translateX: offset.value }],
+
const animatedStyles = useAnimatedStyle(() => ({
+
transform: [{ translateX: withSpring(translateX.value * 2) }],
}));
-
const OFFSET = 40;
+
return (
+
<>
+
<Animated.View style={[styles.box, animatedStyles]} />
+
<View style={styles.container}>
+
<Button onPress={handlePress} title="Click me" />
+
</View>
+
</>
+
);
+
}
+
```
+
+
`useAnimatedStyle` allows access to the shared value's `.value`, enabling operations like multiplication before assigning it to `style`. It also centralizes animation logic.
+
+
### Animating Props
+
+
While many values are animated via the `style` property, sometimes props need animating. For example, SVG elements use props instead of styles:
+
+
```typescript
+
<Circle cx="50" cy="50" r="10" fill="blue" />
+
```
+
+
To animate non-Reanimated components' props, wrap them with `createAnimatedComponent`:
+
+
```typescript
+
import Animated from "react-native-reanimated"
+
import { Circle } from "react-native-svg"
+
+
const AnimatedCircle = Animated.createAnimatedComponent(Circle)
+
```
+
+
Animating the radius of an SVG circle can be done by passing a shared value as a prop:
+
+
```typescript
+
import { useSharedValue } from 'react-native-reanimated';
+
import { Svg } from 'react-native-svg';
+
+
function App() {
+
const r = useSharedValue(10);
+
+
return (
+
<Svg>
+
<AnimatedCircle cx="50" cy="50" r={r} fill="blue" />
+
</Svg>
+
);
+
}
+
```
+
+
For encapsulating animation logic and accessing `.value`, `useAnimatedProps` is used:
+
+
```typescript
+
const AnimatedCircle = Animated.createAnimatedComponent(Circle);
+
+
export default function App() {
+
const r = useSharedValue<number>(20);
const handlePress = () => {
-
offset.value = withTiming(OFFSET);
+
r.value += 10;
};
+
const animatedProps = useAnimatedProps(() => ({
+
r: withTiming(r.value),
+
}));
+
return (
<View style={styles.container}>
-
<Animated.View style={[styles.box, style]} />
-
<Button title="shake" onPress={handlePress} />
+
<Svg style={styles.svg}>
+
<AnimatedCircle
+
cx="50%"
+
cy="50%"
+
fill="#b58df1"
+
animatedProps={animatedProps}
+
/>
+
</Svg>
+
<Button onPress={handlePress} title="Click me" />
</View>
);
```
-
### Repeating an Animation
+
In `useAnimatedProps`, return an object with animatable props, then pass it to the `animatedProps` prop of an Animated component.
-
To create a shake effect, use the `withRepeat` modifier. This allows you to repeat an animation multiple times or indefinitely.
+
### Summary
+
+
- Inline styles are simple but limited for complex animations.
+
- Props differ from styles as they aren't passed via the `style` object.
+
- `useAnimatedStyle` and `useAnimatedProps` provide access to shared values' `.value`, enhancing animation control.
+
- Custom animatable components can be created with `Animated.createAnimatedComponent`.
+
+
### What's Next?
+
+
In the next section, we'll delve into animation functions and customizing their behavior.
+
+
## useFrameCallback in React Native Reanimated (Version: 3.x)
+
+
### Overview
+
+
The `useFrameCallback` hook allows you to execute a function on every frame update within your application.
+
+
### Reference
```typescript
-
import { withRepeat } from "react-native-reanimated"
+
import { useFrameCallback } from 'react-native-reanimated';
function App() {
-
sv.value = withRepeat(withTiming(50), 5)
+
const frameCallback = useFrameCallback((frameInfo) => {
+
// Increment a value with each frame update
+
sv.value += 1;
+
});
+
+
return (
+
<Button
+
title="Start/Stop"
+
onPress={() => frameCallback.setActive(!frameCallback.isActive)}
+
/>
+
);
```
-
Pass a number for repetitions or a non-positive value for infinite repetition. Use `true` as the third argument to reverse the animation direction.
+
#### Arguments
-
Updated example:
+
##### `callback`
+
+
- A function that runs on every frame update.
+
- Receives a `frameInfo` object with the following properties:
+
- `timestamp`: The system time (in milliseconds) when the last frame was rendered.
+
- `timeSincePreviousFrame`: Time (in milliseconds) since the previous frame. This is `null` for the first frame after activation and approximately 16 ms on a 60 Hz display or 8 ms on a 120 Hz display, assuming no frames are dropped.
+
- `timeSinceFirstFrame`: The time (in milliseconds) elapsed since the callback was activated.
+
+
##### `autostart` (Optional)
+
+
- Determines if the callback should start automatically. Defaults to `true`.
+
+
#### Returns
+
+
The `useFrameCallback` hook returns an object with these properties:
+
+
- `setActive`: A function to start or stop the frame callback.
+
- `isActive`: A boolean indicating whether the callback is currently running.
+
- `callbackId`: A unique identifier for the frame callback.
+
+
### Remarks
+
+
- The function provided in the `callback` argument is automatically workletized and executed on the UI thread.
+
+
### Platform Compatibility
+
+
|Android|iOS|Web|
+
|-|-|-|
+
|✅|✅|✅|
+
+
- Reference
+
- Arguments
+
- Returns
+
- Example
+
- Remarks
+
- Platform compatibility
+
+
## Handling gestures
+
+
This section covers handling gestures using Reanimated in conjunction with React Native Gesture Handler. We'll focus on `Tap` and `Pan` gestures and introduce the `withDecay` animation function.
+
+
Ensure you've completed the Gesture Handler installation steps before proceeding.
+
+
### Handling Tap Gestures
+
+
We begin with tap gestures, which detect brief screen touches. These can be used for custom buttons or pressable elements.
+
+
In this example, a circle grows and changes color upon touch.
+
+
First, wrap your app in `GestureHandlerRootView` to ensure gesture functionality:
+
+
```typescript
+
import { GestureHandlerRootView } from 'react-native-gesture-handler';
+
+
function App() {
+
return (
+
<GestureHandlerRootView style={{ flex: 1 }}>
+
{/* rest of the app */}
+
</GestureHandlerRootView>
+
);
+
}
+
```
+
+
Define tap gestures using `Gesture.Tap()` and chain methods like `onBegin`, `onStart`, `onEnd`, or `onFinalize` to update shared values:
```typescript
export default function App() {
-
const offset = useSharedValue<number>(0);
+
const pressed = useSharedValue<boolean>(false);
-
const style = useAnimatedStyle(() => ({
-
transform: [{ translateX: offset.value }],
-
}));
+
const tap = Gesture.Tap()
+
.onBegin(() => {
+
pressed.value = true;
+
})
+
.onFinalize(() => {
+
pressed.value = false;
+
});
+
```
-
const OFFSET = 40;
+
Access shared values safely as gesture callbacks are automatically workletized.
+
+
Define animation logic using `withTiming` in `useAnimatedStyle`:
+
+
```typescript
+
const animatedStyles = useAnimatedStyle(() => ({
+
backgroundColor: pressed.value ? "#FFE04B" : "#B58DF1",
+
transform: [{ scale: withTiming(pressed.value ? 1.2 : 1) }],
+
}))
+
```
-
const handlePress = () => {
-
offset.value = withRepeat(withTiming(OFFSET), 5, true);
-
};
+
Pass the gesture to `GestureDetector` and apply `animatedStyles`:
+
```typescript
return (
-
<View style={styles.container}>
-
<Animated.View style={[styles.box, style]} />
-
<Button title="shake" onPress={handlePress} />
-
</View>
+
<GestureHandlerRootView style={styles.container}>
+
<View style={styles.container}>
+
<GestureDetector gesture={tap}>
+
<Animated.View style={[styles.circle, animatedStyles]} />
+
</GestureDetector>
+
</View>
+
</GestureHandlerRootView>
);
```
-
### Running Animations in a Sequence
+
### Handling Pan Gestures
+
+
Enhance the circle by making it draggable and bouncing back to its starting position upon release. Retain color highlight and scale effects.
+
+
Switch from `Tap` to `Pan` gesture and add an `onChange` method:
+
+
```typescript
+
const offset = useSharedValue<number>(0);
+
+
const pan = Gesture.Pan()
+
.onBegin(() => {
+
pressed.value = true;
+
})
+
.onChange((event) => {
+
offset.value = event.translationX;
+
})
+
.onFinalize(() => {
+
offset.value = withSpring(0);
+
pressed.value = false;
+
```
-
To enhance the animation, use `withSequence` to chain animations. This modifier starts the next animation when the previous one ends.
+
Use `translationX` from the event data to move the circle. Reset `offset.value` in `onFinalize` using `withSpring`.
+
+
Adjust `useAnimatedStyle` for handling offset:
```typescript
-
import { withSequence } from "react-native-reanimated"
+
const animatedStyles = useAnimatedStyle(() => ({
+
transform: [
+
{ translateX: offset.value },
+
{ scale: withTiming(pressed.value ? 1.2 : 1) },
+
],
+
backgroundColor: pressed.value ? "#FFE04B" : "#b58df1",
+
}))
+
```
+
+
### Using `withDecay`
+
+
`withDecay` retains gesture velocity for decelerating animations.
+
+
Pass final velocity in `onFinalize` to `withDecay`:
+
+
```typescript
+
const pan = Gesture.Pan()
+
.onChange((event) => {
+
offset.value += event.changeX;
+
})
+
.onFinalize((event) => {
+
offset.value = withDecay({
+
velocity: event.velocityX,
+
rubberBandEffect: true,
+
clamp: [
+
-(width.value / 2) + SIZE / 2 + BOUNDARY_OFFSET,
+
width.value / 2 - SIZE / 2 - BOUNDARY_OFFSET,
+
```
+
+
Ensure the square stays within screen bounds.
+
+
Explore `withDecay` API for more configuration options.
+
+
### Summary
+
+
This section covered gesture handling with Reanimated and Gesture Handler, focusing on `Tap`, `Pan`, and `withDecay`. Key points include:
+
+
- Integration of Reanimated with React Native Gesture Handler.
+
- Creation of gestures like `Gesture.Pan()` or `Gesture.Tap()`.
+
- Accessing shared values in gesture callbacks without extra boilerplate.
+
- Using `withDecay` for decelerating animations based on gesture velocity.
+
+
### What's Next?
+
+
Explore further gestures such as Pinch and Fling by reviewing the React Native Gesture Handler documentation. The next section will delve into a glossary of terms.
+
+
## withRepeat
+
+
`withRepeat` is an animation modifier that allows you to repeat a specified animation a certain number of times or indefinitely.
+
+
### Reference
+
+
```typescript
+
import { withRepeat } from "react-native-reanimated"
function App() {
-
sv.value = withSequence(withTiming(50), withTiming(0))
+
sv.value = withRepeat(withSpring(0), 5)
+
// ...
```
-
Improved example:
+
#### Arguments
+
+
##### `animation`
+
+
The animation object you wish to repeat.
+
+
##### `numberOfReps` (Optional)
+
+
Specifies how many times the animation should be repeated. The default is `2`.
+
+
A non-positive value, such as `0` or `-1`, will cause the animation to repeat indefinitely until it is canceled or removed. For instance, if the component unmounts or `cancelAnimation` is invoked.
+
+
##### `reverse` (Optional)
+
+
Determines whether the animation should alternate directions with each repetition. The default setting is `false`.
+
+
This feature only supports direct animation functions like `withSpring` and does not work with other animation modifiers such as `withSequence`.
+
+
##### `callback` (Optional)
+
+
A function that executes upon the completion of the animation. If the animation is canceled, the callback receives `false`; otherwise, it receives `true`.
+
+
##### `reduceMotion` (Optional)
+
+
Controls how the animation responds to the device's reduced motion accessibility setting.
+
+
#### Returns
+
+
The `withRepeat` function returns an animation object representing the current state of the animation. This can be directly assigned to a shared value or used as a style object returned from `useAnimatedStyle`.
+
+
### Remarks
+
+
- The callback provided in the fourth argument is automatically workletized and executed on the UI thread.
+
+
### Platform Compatibility
+
+
|Android|iOS|Web|
+
|-|-|-|
+
|✅|✅|✅|
+
+
## useComposedEventHandler
+
+
The `useComposedEventHandler` hook allows you to combine multiple event handlers, such as those created with `useAnimatedScrollHandler`, into a single handler.
+
+
### Reference Example
```typescript
-
const TIME = 250
+
import Animated, {
+
useAnimatedScrollHandler,
+
useComposedEventHandler,
+
} from 'react-native-reanimated';
+
+
function ComposedEventHandlerExample() {
+
const onScrollHandler1 = useAnimatedScrollHandler({
+
onScroll(e) {
+
console.log('Scroll handler 1 onScroll event');
+
},
+
});
+
+
const onScrollHandler2 = useAnimatedScrollHandler({
+
onScroll(e) {
+
console.log('Scroll handler 2 onScroll event');
+
},
+
});
+
+
const composedHandler = useComposedEventHandler([
+
onScrollHandler1,
+
onScrollHandler2,
+
]);
-
const handlePress = () => {
-
offset.value = withSequence(
-
// start from -OFFSET
-
withTiming(-OFFSET, { duration: TIME / 2 }),
-
// shake between -OFFSET and OFFSET 5 times
-
withRepeat(withTiming(OFFSET, { duration: TIME }), 5, true),
-
// go back to 0 at the end
-
withTiming(0, { duration: TIME / 2 })
-
)
+
return (
+
<View style={styles.container}>
+
<Animated.ScrollView style={styles.scroll} onScroll={composedHandler}>
+
<Content />
+
</Animated.ScrollView>
+
</View>
+
);
```
-
### Starting the Animation with Delay
+
#### Arguments
+
+
- **`handlers`**: An array of event handlers created using the `useEvent` hook. The `useComposedEventHandler` hook updates whenever there are changes in these handlers.
+
+
#### Returns
+
+
The hook returns a handler object that can be used with any `Animated component`. This handler should be assigned to the corresponding `onEvent` prop (e.g., `onScroll` for scroll-related handlers). For better code clarity, it's recommended to use multiple composed handlers if your aggregated handler manages various events.
+
+
### Remarks
+
+
- The returned handler combines the functionalities of all provided handlers. This allows multiple handlers to respond to a single event and manage different types of events with one object.
+
- It functions effectively when used with multiple `Animated components`, triggering event callbacks for each connected component.
+
+
### Platform Compatibility
+
+
|Android|iOS|Web|
+
|-|-|-|
+
|✅|✅|✅|
+
+
## withDelay
+
+
`withDelay` is an animation modifier that allows you to initiate an animation after a specified delay period.
-
Add suspense by delaying the animation start using `withDelay`.
+
### Reference
```typescript
import { withDelay } from "react-native-reanimated"
function App() {
sv.value = withDelay(500, withTiming(0))
+
// ...
```
-
Final example:
+
#### Arguments
+
+
- **`delayMs`**: Specifies the duration (in milliseconds) before the animation begins.
+
+
- **`delayedAnimation`**: The animation that will be delayed.
+
+
- **`reduceMotion`** *(Optional)*: Determines how the animation responds to the device's reduced motion accessibility setting.
+
+
#### Returns
+
+
The `withDelay` function returns an animation object representing the current state of the animation. This object can either be directly assigned to a shared value or used as a value for a style object returned from `useAnimatedStyle`.
+
+
### Example
+
+
*(Example content would go here)*
+
+
### Platform Compatibility
+
+
|Android|iOS|Web|
+
|-|-|-|
+
|✅|✅|✅|
+
+
***
+
+
## useAnimatedSensor
+
+
`useAnimatedSensor` allows you to create animations based on device sensor data. It provides access to:
+
+
- **Accelerometer**: Measures device acceleration (excluding gravity) along the x, y, and z axes.
+
- **Gyroscope**: Captures the rotation rate of the device along the x, y, and z axes.
+
- **Gravity**: Provides the current gravity vector along the x, y, and z axes.
+
- **Magnetic Field**: Measures the Earth's magnetic field strength and direction in microtesla (μT).
+
- **Rotation**: Represents the device orientation using Euler angles and a quaternion.
+
+
For comprehensive documentation, refer to the Sensors guide on Android Developers and Device Motion in Apple Developer documentation.
+
+
### Reference
```typescript
-
const OFFSET = 40
-
const TIME = 250
-
const DELAY = 400
+
import { useAnimatedSensor, SensorType } from "react-native-reanimated"
+
+
function App() {
+
const gyroscope = useAnimatedSensor(SensorType.GYROSCOPE)
-
const handlePress = () => {
-
offset.value = withDelay(
-
DELAY,
-
withSequence(
-
// start from -OFFSET
-
withTiming(-OFFSET, { duration: TIME / 2 }),
-
// shake between -OFFSET and OFFSET 5 times
-
withRepeat(withTiming(OFFSET, { duration: TIME }), 5, true),
-
// go back to 0 at the end
-
withTiming(0, { duration: TIME / 2 })
-
)
-
)
+
useDerivedValue(() => {
+
const { x, y, z } = gyroscope.sensor.value
+
})
```
-
### Summary
+
#### Arguments
-
- **Modifiers**: `withRepeat`, `withSequence`, and `withDelay`.
-
- **`withRepeat`**: Repeats an animation a specified number of times or indefinitely.
-
- **`withSequence`**: Chains animations to run sequentially.
-
- **`withDelay`**: Delays the start of an animation.
+
##### `sensorType`
-
### What's Next?
+
Specifies the sensor type using a `SensorType` enum:
-
Explore handling `Tap` and `Pan` gestures, and learn about the `withDecay` animation function.
+
- `ACCELEROMETER`: Measures device acceleration in m/s².
+
- `GYROSCOPE`: Captures rotation rate in radians per second.
+
- `GRAVITY`: Provides gravity vector in m/s².
+
- `MAGNETIC_FIELD`: Measures magnetic field strength in microtesla (μT).
+
- `ROTATION`: Represents orientation using Euler angles and a quaternion.
-
````markdown
-
# `useAnimatedScrollHandler`
+
##### `config` (Optional)
-
The `useAnimatedScrollHandler` is a custom hook designed to provide an event handler for managing animated scrolling within React Native applications. This hook integrates seamlessly with various scrollable components, enabling developers to implement smooth and responsive animations.
+
|Name|Type|Default|Description|
+
|-|-|-|-|
+
|interval|`number \| "auto"`|`"auto"`|Time between sensor readings in milliseconds. `"auto"` matches the device's screen refresh rate.|
+
|adjustToInterfaceOrientation|`boolean`|`true`|Adjusts measurements to the current interface orientation.|
+
|iosReferenceFrame|`IOSReferenceFrame`|`IOSReferenceFrame.Auto`|Frame of reference for iOS sensors.|
-
## Usage
+
Available `IOSReferenceFrame` options:
-
To utilize the `useAnimatedScrollHandler`, you need to import it from its respective library or module where it's defined. Once imported, this hook can be invoked within a functional component to obtain an event handler reference that is specifically tailored for animated scroll events.
+
- `xArbitraryZVertical`: Z axis is vertical, X axis arbitrary in horizontal plane.
+
- `xArbitraryCorrectedZVertical`: Improved rotation accuracy with Z vertical and X arbitrary.
+
- `XMagneticNorthZVertical`: Z axis vertical, X points to magnetic north.
+
- `XTrueNorthZVertical`: Z axis vertical, X points to geographic north.
+
- `Auto`: Defaults based on device capabilities.
+
+
#### Returns
+
+
`useAnimatedSensor` returns an object:
+
+
|Name|Type|Description|
+
|-|-|-|
+
|sensor|`SharedValue<Value3D \| ValueRotation>`|Shared value with sensor measurements.|
+
|unregister|`() => void`|Stops listening to sensor updates when called.|
+
|isAvailable|`boolean`|Indicates if the sensor is available for use.|
+
|config|`SensorConfig`|Contains sensor configuration details.|
+
+
The shared value from the **rotation sensor** includes:
+
+
- Euler angles: `roll`, `pitch`, `yaw`.
+
- Quaternion components: `qw`, `qx`, `qy`, `qz`.
+
- Interface orientation.
+
+
Other sensors return measurements on x, y, z axes and interface orientation.
+
+
`InterfaceOrientation` enum values:
+
+
- `ROTATION_0`: Default rotation on Android, portrait on iOS.
+
- `ROTATION_90`: 90 degrees on Android, landscape right on iOS.
+
- `ROTATION_180`: 180 degrees on Android, upside down on iOS.
+
- `ROTATION_270`: 270 degrees on Android, landscape left on iOS.
### Example
-
Below is a basic example demonstrating how to use `useAnimatedScrollHandler` in conjunction with a React Native ScrollView:
+
```typescript
+
export default function App() {
+
const gravity = useAnimatedSensor(SensorType.GRAVITY);
+
+
const animatedStyle = useAnimatedStyle(() => {
+
return {
+
transform: [
+
{ translateX: withSpring(gravity.sensor.value.x * 20) },
+
{ translateY: withSpring(gravity.sensor.value.y * 20) },
+
],
+
};
+
});
+
+
return (
+
<View style={styles.container}>
+
<Animated.View style={[styles.box, animatedStyle]} />
+
</View>
+
);
+
}
+
```
+
+
### Remarks
+
+
- On iOS, enable location services (`Settings > Privacy > Location Services`) to read sensor data.
+
- On Web, ensure the device supports sensors and the application is served over HTTPS.
+
- Most sensors operate at resolutions up to 100Hz.
+
- Sensor data can be accessed on both UI and JavaScript threads.
+
+
### Platform Compatibility
+
+
|Android|iOS|Web|
+
|-|-|-|
+
|✅|✅|✅|
+
+
## dispatchCommand
+
+
The `dispatchCommand` function enables the execution of commands directly on a native component from the UI thread.
+
+
### Reference
```typescript
-
import { useAnimatedScrollHandler } from 'react-native-reanimated';
-
import { ScrollView, View, Text } from 'react-native';
+
import { dispatchCommand } from 'react-native-reanimated';
-
const MyComponent = () => {
-
const scrollHandler = useAnimatedScrollHandler({
-
onScroll: (event) => {
-
// Handle the scroll event with animation logic here
-
console.log(event.contentOffset);
-
},
+
function App() {
+
const animatedRef = useAnimatedRef();
+
+
const gesture = Gesture.Tap().onStart(() => {
+
dispatchCommand(animatedRef, 'focus');
});
return (
-
<ScrollView
-
horizontal
-
pagingEnabled
-
showsHorizontalScrollIndicator={false}
-
onScroll={scrollHandler}
-
>
-
{/* Your content goes here */}
-
<View style={{ width: '100%', height: 200, backgroundColor: 'red' }} />
-
<View style={{ width: '100%', height: 200, backgroundColor: 'blue' }} />
-
<View style={{ width: '100%', height: 200, backgroundColor: 'green' }} />
-
</ScrollView>
+
<>
+
<AnimatedTextInput ref={animatedRef} style={styles.input} />
+
<GestureDetector gesture={gesture}>
+
<Button title="Focus" />
+
</GestureDetector>
+
</>
);
-
};
+
}
+
```
-
export default MyComponent;
+
#### Arguments
+
+
- **`animatedRef`**: An animated reference linked to the component you wish to update. This reference must be associated with either an Animated component or a React Native built-in component.
+
+
- **`commandName`**: The name of the command to execute, such as `'focus'` or `'scrollToEnd'`.
+
+
- **`args` (Optional)**: An array of arguments for the command. Defaults to an empty array if not provided.
+
+
### Example
+
+
```typescript
+
const goDown = Gesture.Tap().onStart(() => {
+
dispatchCommand(tosRef, "scrollToEnd", [true])
+
dispatchCommand(loginRef, "focus")
+
})
```
-
````
-
In this example, `useAnimatedScrollHandler` is used to create a scroll handler that logs the current content offset whenever a scroll event occurs. This setup allows for enhanced control over scrolling animations within the component.
+
### Remarks
-
### Parameters
+
- Commands vary depending on the component. Refer to the relevant React Native documentation for available commands specific to each component.
-
The hook accepts an object with various properties that define how the scroll events should be handled:
+
### Platform Compatibility
-
- **onScroll**: A function that receives the scroll event details, such as `contentOffset`, and can contain logic to animate or respond to the scroll action.
-
- Additional optional parameters may include `onBeginDrag`, `onActiveDrag`, `onEndDrag`, etc., depending on the specific requirements of your animation.
+
|Android|iOS|Web|
+
|-|-|-|
+
|✅|✅|❌|
-
### Benefits
+
## setNativeProps
-
Using `useAnimatedScrollHandler` offers several advantages:
+
The `setNativeProps` function allows for the imperative updating of component properties in React Native. It serves as an escape hatch intended for specific edge cases.
-
- **Performance**: By leveraging React Native Reanimated, this hook ensures that animations are performed smoothly and efficiently.
-
- **Flexibility**: Developers can customize scroll behavior extensively through various event handlers.
-
- **Integration**: Seamlessly works with existing React Native components like ScrollView, FlatList, etc.
+
> **Caution:**\
+
> Prefer using `useAnimatedStyle` and `useAnimatedProps` when animating styles or properties, reserving `setNativeProps` for exceptional situations.
-
By incorporating `useAnimatedScrollHandler` into your project, you can enhance the user experience with fluid and responsive scrolling animations.
+
### Reference
-
````
+
```typescript
+
import { setNativeProps } from 'react-native-reanimated';
+
+
function App() {
+
const animatedRef = useAnimatedRef();
+
+
const tap = Gesture.Tap().onEnd(() => {
+
setNativeProps(animatedRef, { text: '' });
+
});
+
+
return <TextInput ref={animatedRef} />;
+
}
+
```
+
+
#### Arguments
+
+
- **`animatedRef`:**\
+
An animated reference linked to the component you wish to update. This animated reference must be passed either to an Animated component or a React Native built-in component.
+
+
- **`updates`:**\
+
An object containing properties that need updating, which can include both style properties (e.g., `width`, `backgroundColor`) and regular properties (e.g., `text`).
+
+
#### Returns
+
+
The function returns `undefined`.
+
+
### Remarks
+
+
- Prioritize using `useAnimatedStyle` and `useAnimatedProps` for animating styles or properties.
+
- Ensure that `setNativeProps` is used exclusively on the UI thread.
+
- The `setNativeProps` function was designed to facilitate the imperative updating of props from gesture handlers. In other scenarios, it may require an additional `runOnUI` call, making React Native's built-in `setNativeProps` more efficient with fewer runtime transitions.
+
+
### Platform Compatibility
+
+
|Android|iOS|Web|
+
|-|-|-|
+
|✅|✅|✅|
+
+
***
+
+
## React Native Reanimated: useReducedMotion Hook (Version 3.x)
-
# Interpolation with `react-native-reanimated`
+
### Overview
-
The `interpolate` function is used to map a numeric value from one specified range to another using linear interpolation.
+
The `useReducedMotion` hook in React Native Reanimated allows developers to check the system's reduced motion setting. This is particularly useful for disabling animations when users prefer less motion.
-
## Reference Usage
+
### Reference
```typescript
-
import { interpolate, Extrapolation } from 'react-native-reanimated';
+
import { useReducedMotion } from "react-native-reanimated"
function App() {
-
const animatedStyle = useAnimatedStyle(() => ({
-
opacity: interpolate(sv.value, [0, 100], [0, 1], Extrapolation.CLAMP),
-
}));
+
const reduceMotion = useReducedMotion()
+
+
if (reduceMotion) {
+
// Display static content ✨
+
} else {
+
// Run animations ✨
+
}
+
+
// Additional logic...
-
````
+
```
-
#### Parameters
+
#### Returns
-
- **`value`**: A numeric value that will be mapped to the specified `output` range.
+
The `useReducedMotion` hook returns a boolean value indicating whether the reduced motion setting was enabled at the start of the app.
-
- **`input`**: An array of numbers defining the input range for interpolation.
+
### Example Usage
-
- **`output`**: An array of numbers defining the output range for interpolation, which should have at least as many points as the input range.
+
```typescript
+
import { useReducedMotion } from 'react-native-reanimated';
-
- **`extrapolate` (Optional)**: Determines behavior when `value` is outside the `input` range. Defaults to `Extrapolation.EXTEND`.
+
function App() {
+
const reduceMotion = useReducedMotion();
-
Available options:
+
if (reduceMotion) {
+
return <StaticContent />;
+
} else {
+
return <AnimatedContent />;
+
}
+
}
+
```
-
- `Extrapolation.EXTEND`: Predicts values beyond the output range.
-
- `Extrapolation.CLAMP`: Clamps the value to the edge of the output range.
-
- `Extrapolation.IDENTITY`: Returns the provided value unchanged.
+
### Remarks
-
String equivalents include `"extend"`, `"clamp"`, and `"identity"`.
+
- Changing the reduced motion setting does not trigger a component rerender.
+
- Unlike `AccessibilityInfo.isReduceMotionEnabled()`, `useReducedMotion` provides the value synchronously.
+
+
### Platform Compatibility
+
+
|Android|iOS|Web|
+
|-|-|-|
+
|✅|✅|✅|
+
+
This hook is compatible across Android, iOS, and Web platforms.
+
+
## makeMutable
+
+
**Caution:** The use of `makeMutable` is generally discouraged. It's recommended to opt for the `useSharedValue` hook unless you are fully aware of its implications (refer to the Remarks section).
-
To apply extrapolation to a specific edge, use an object:
+
Internally, `makeMutable` is utilized by the `useSharedValue` hook to generate a shared value. This function allows the creation of mutable values without relying on the hook, which can be beneficial in specific scenarios such as within the global scope or when managing an array of mutable values.
-
```typescript
-
const opacity = interpolate(sv.value, [0, 100], [0, 1], {
-
extrapolateLeft: Extrapolation.CLAMP,
-
})
-
```
+
The object produced by `makeMutable` mirrors that returned by the `useSharedValue` hook, ensuring consistent usage thereafter.
-
#### Return Value
+
### Reference
-
The `interpolate` function returns a value mapped within the specified output range.
+
```typescript
+
import { makeMutable } from "react-native-reanimated"
+
+
const mv = makeMutable(100)
+
```
+
+
#### Arguments
+
+
##### `initial`
+
+
This argument specifies the initial value to be stored in the mutable. It can encompass any JavaScript data type such as `number`, `string`, or `boolean`, and also includes complex structures like arrays and objects.
+
+
#### Returns
+
+
`makeMutable` yields a mutable value initialized with the provided `initial`. Access to the stored data is possible through its `value` property or via `get` and `set` methods.
+
+
### Example
+
+
### Remarks
+
+
**Info:** The term *mutable value* refers to an object created by `makeMutable`, distinguishing it from a *shared value*, which is essentially a mutable value with automatic cleanup.
+
+
- All remarks applicable to the `useSharedValue` hook are relevant to `makeMutable`.
+
- Avoid invoking `makeMutable` directly within component scope. Component re-renders will generate a new object, potentially resetting the initial value and losing previous state.
+
+
```typescript
+
function App() {
+
const [counter, setCounter] = useState(0)
+
const mv = makeMutable(counter) // 🚨 creates a new mutable value on each render
+
+
useEffect(() => {
+
const interval = setInterval(() => {
+
setCounter((prev) => prev + 1) // updates the counter stored in component state
+
}, 1000)
+
+
return () => {
+
clearInterval(interval)
+
}
+
}, [mv])
+
+
useAnimatedReaction(
+
() => mv.value,
+
(value) => {
+
console.log(value) // prints 0, 1, 2, ...
+
}
+
)
+
}
+
```
+
+
- Utilize `cancelAnimation` to halt all ongoing animations on a mutable value if it becomes unnecessary and animations are still active. Exercise caution with infinite animations as they require manual cancellation.
+
+
```typescript
+
function App() {
+
const mv = useMemo(() => makeMutable(0), [])
+
+
useEffect(() => {
+
mv.value = withRepeat(withSpring(100), -1, true) // creates an infinite animation
+
+
return () => {
+
cancelAnimation(mv) // ✅ stops the infinite animation on component unmount
+
}
+
}, [])
+
}
+
```
+
+
- `cancelAnimation` is not needed for non-animated values as they are automatically garbage collected when no references remain.
+
+
```typescript
+
const someFlag = makeMutable(false)
+
+
function App() {
+
someFlag.value = true // ✅ no need to cancel the animation later on
+
}
+
```
+
+
- When opting for `makeMutable`, adhere to React's rules and avoid common pitfalls associated with `useRef`, such as modifying references during rendering (see the **Pitfall** section in the useRef documentation).
+
+
#### Comparison with `useSharedValue`
+
+
|Feature|`makeMutable`|`useSharedValue`|
+
|-|-|-|
+
|Object Creation|Creates a new object on each call|Reuses the same object on each call|
+
|Initial Value Change|A new object is created if `initial` changes|The initially created object remains unchanged if `initialValue` changes|
+
|Scope Usage|Can be used outside of component scope|Limited to use within component scope|
+
|Loop Usage|Usable in loops with variable iterations|Usable in loops only if the number of hooks (`useSharedValue` calls) is constant|
+
|Animation Cancellation|Does not automatically cancel animations on unmount|Automatically cancels animations when the component unmounts|
### Platform Compatibility
···
|-|-|-|
|✅|✅|✅|
-
## Clamp Function in React Native Reanimated
+
## Accurate Call Stacks
+
+
When debugging Reanimated code, developers might encounter misleading call stacks in errors or warnings. These stacks often highlight internal Reanimated code rather than pinpointing the misuse of the Reanimated API that caused the issue.
+
+
To improve this situation, Reanimated offers a Metro configuration wrapper named `wrapWithReanimatedMetroConfig`. This tool adjusts your Metro config to enhance the accuracy of call stacks for warnings and errors generated by the Reanimated library.
+
+
### Reference
+
+
For more precise call stacks, import `wrapWithReanimatedMetroConfig` from `react-native-reanimated/metro-config` and use it to wrap your existing Metro configuration in the `metro.config.js` file.
+
+
```typescript
+
// metro.config.js
+
import { wrapWithReanimatedMetroConfig } from "react-native-reanimated/metro-config"
+
+
const config = {
+
// Your existing Metro configuration options
+
}
+
+
export default wrapWithReanimatedMetroConfig(config)
+
```
+
+
### Example
+
+
The example below illustrates the difference in call stacks before and after applying the Reanimated Metro config wrapper. The **Before** scenario shows Reanimated source code as the error origin, while the **After** scenario reveals the actual incorrect code that caused the error.
+
+
|Before|After|
+
|-|-|
+
|||
+
+
### Remarks
+
+
- `wrapWithReanimatedMetroConfig` does not remove any stack frames; it only collapses irrelevant ones from Reanimated. To inspect these, you can expand collapsed stack frames by clicking on the **See N more frames** text at the bottom of the **Call Stack**.
+
+
|Collapsed|Expanded|
+
|-|-|
+
|||
+
+
- Some errors, especially those arising from asynchronous code, may still point to Reanimated internals instead of the exact problematic line in your code. This happens because stack traces can lose track of the original code that initiated the asynchronous operation. In such cases, manual debugging based on the error message is necessary to identify the potential cause of the problem.
+
+
## withClamp
-
The `clamp` function is used to restrict a value within a specified range, ensuring it does not exceed the defined minimum and maximum bounds.
+
`withClamp` is an animation modifier that restricts the movement of your animation within a specified range. It's typically used in conjunction with `withSpring`.
### Reference
```typescript
-
import { clamp } from "react-native-reanimated"
+
import { withClamp } from "react-native-reanimated"
function App() {
-
const result = clamp(sv.value, 0, 100)
+
sv.value = withClamp({ min: -1, max: 1 }, withSpring(0))
+
// ...
```
#### Arguments
-
- **`value`**: A numeric value that will be returned if it falls within the specified `min` and `max` range.
+
##### `config`
+
+
An object containing the following properties:
+
+
|Name|Type|Description|
+
|-|-|-|
+
|min|number|Optional. The lowest value your animation can reach.|
+
|max|number|Optional. The highest value your animation can reach.|
-
- **`min`**: The lower bound. If the provided `value` is less than this number, `min` will be returned.
+
##### `animation`
+
+
The spring animation you wish to clamp.
-
- **`max`**: The upper bound. If the provided `value` exceeds this number, `max` will be returned.
+
```typescript
+
const clampedStyleWithDelay = useAnimatedStyle(() => {
+
return {
+
width: withClamp({ min: 0, max: 100 }, withSpring(randomWidth.value)),
+
}
+
})
+
```
#### Returns
-
The function returns a numeric value that lies between the specified `min` and `max` bounds.
+
`withClamp` returns an animation object. This can be directly assigned to a shared value or used as a style value in `useAnimatedStyle`.
+
+
|Platform|Supported|
+
|-|-|
+
|Android|✅|
+
|iOS|✅|
+
|Web|✅|
+
+
## Logger configuration
+
+
Reanimated provides warnings to highlight potential misuses of its API, such as altering shared values during component re-renders. These logs can be adjusted in verbosity.
+
+
By default, the logger configuration requires no setup and displays all warnings and errors. To customize this behavior, use the `configureReanimatedLogger` function.
+
+
### Reference
+
+
To alter the default Reanimated logger settings, import `configureReanimatedLogger` from `react-native-reanimated` and invoke it with your desired configuration:
+
+
```typescript
+
import {
+
configureReanimatedLogger,
+
ReanimatedLogLevel,
+
} from "react-native-reanimated"
+
+
// Default configuration example
+
configureReanimatedLogger({
+
level: ReanimatedLogLevel.warn,
+
strict: true, // Strict mode is enabled by default
+
})
+
```
+
+
#### Configuration Options
+
+
- **`level`:** Specifies the minimum log level to display using a value from `ReanimatedLogLevel`.
+
+
- **`strict`:** A boolean that toggles strict mode. Enabling it results in additional warnings to help identify potential code issues.
+
+
### Remarks
+
+
- The logger configuration is global, affecting all Reanimated warnings and errors. It cannot be configured on a per-file or per-component basis.
+
+
- Call `configureReanimatedLogger` before creating any Reanimated animations, typically in the root file of your application.
-
### Example Usage
+
- This function is intended for app developers. Library creators using Reanimated should avoid including this call in their source code to prevent overriding users' configurations with the default settings.
+
+
### Platform Compatibility
+
+
|Android|iOS|Web|
+
|-|-|-|
+
|✅|✅|✅|
+
+
## React Native Reanimated: ReducedMotionConfig
+
+
**Version:** 3.x
+
+
### Overview
+
+
The `ReducedMotionConfig` component allows you to modify the behavior of animations based on a device's reduced motion accessibility setting. By default, it disables all animations when this setting is enabled. You can customize this behavior according to your specific needs. For more information about Accessibility and `useReducedMotion`, refer to Reanimated documentation.
+
+
> **Caution:** The new configuration will be applied globally across the entire application.
+
+
### Reference
```typescript
-
import { clamp } from "react-native-reanimated"
+
import { ReducedMotionConfig, ReduceMotion } from 'react-native-reanimated';
function App() {
-
const constrainedValue = clamp(150, 0, 100) // Result will be 100
+
return (
+
// ...
+
<ReducedMotionConfig mode={ReduceMotion.Never} />
+
// ...
+
);
```
+
#### Arguments
+
+
##### `mode`
+
+
This parameter determines how animations should respond to the device's reduced motion accessibility setting:
+
+
- **`ReduceMotion.System`:** Adjusts animation behavior based on the device's reduced motion setting. Animations are disabled when this setting is enabled; otherwise, they remain active.
+
+
- **`ReduceMotion.Always`:** Consistently disables animations, regardless of the device's accessibility configuration.
+
+
- **`ReduceMotion.Never`:** Ensures that animations remain enabled at all times.
+
### Platform Compatibility
|Android|iOS|Web|
|-|-|-|
|✅|✅|✅|
-
This function is compatible across Android, iOS, and Web platforms.
+
- Reference
+
- Arguments
+
- Example
+
- Platform compatibility
+
+
## Worklets
-
## interpolateColor Function
+
Worklets are short-running JavaScript functions that execute on the UI thread, enabling efficient style calculations and event reactions. Reanimated leverages worklets for these tasks.
-
The `interpolateColor` function maps an input range to output colors using linear interpolation. This is particularly useful in animations where you want a smooth transition between colors.
+
### Creating Worklets
-
### Reference Example
+
To define a custom worklet, use the `'worklet';` directive at the start of your function:
```typescript
-
import { interpolateColor } from 'react-native-reanimated';
+
function myWorklet() {
+
"worklet"
+
console.log("Hello from a worklet")
+
}
+
```
+
+
The Reanimated Babel Plugin identifies functions marked with `'worklet'`, transforming them into serializable objects—a process known as workletization. These objects can then be executed on the UI thread.
+
+
### Automatic Workletization
+
+
When using Reanimated and Gesture Handler, code is typically automatically workletized and executed on the UI thread:
+
+
```typescript
+
import { useAnimatedStyle } from "react-native-reanimated"
function App() {
-
const progress = useSharedValue(0);
+
const style = useAnimatedStyle(() => {
+
// Executed on the UI thread
+
return { opacity: 0.5 }
+
})
+
}
+
```
+
+
### Manual Worklet Execution
+
+
To manually schedule worklet execution, use `runOnUI`:
-
const animatedStyle = useAnimatedStyle(() => {
-
return {
-
backgroundColor: interpolateColor(
-
progress.value,
-
[0, 1],
-
['red', 'green']
-
),
-
};
-
});
+
```typescript
+
function myWorklet() {
+
"worklet"
+
console.log("Hello from the UI thread")
+
}
+
function onPress() {
+
runOnUI(myWorklet)()
+
}
+
```
+
+
Arguments can be passed to worklets as follows:
+
+
```typescript
+
function myWorklet(greeting: string) {
+
"worklet"
+
console.log(`${greeting} from the UI thread`)
+
}
+
+
function onPress() {
+
runOnUI(myWorklet)("Howdy")
+
}
+
```
+
+
### Worklet Closures
+
+
Worklets are closures, allowing them to access variables declared outside their scope. Only referenced variables are captured:
+
+
```typescript
+
const width = 135.5
+
+
function otherWorklet() {
+
"worklet"
+
console.log("Captured width is", width)
+
}
+
```
+
+
Avoid capturing large objects within worklets to prevent performance issues:
+
+
```typescript
+
const theme = {...}; // Large object
+
+
function myWorklet() {
+
'worklet';
+
console.log(theme.color); // 🚨 Captures entire `theme` object
+
}
+
```
+
+
To mitigate this, assign the needed property to a separate variable:
+
+
```typescript
+
const theme = {...};
+
const color = theme.color;
+
+
function myWorklet() {
+
'worklet';
+
console.log(color); // ✅ Captures only `color`
+
}
+
```
+
+
### Returning Data
+
+
Worklets can return data within the same thread:
+
+
```typescript
+
function returningWorklet() {
+
"worklet"
+
return "I'm back" // On the UI thread
+
}
+
+
function someWorklet() {
+
"worklet"
+
const what = returningWorklet() // Still on the UI thread
+
console.log("On the UI thread, other worklet says", what)
+
}
+
```
+
+
### Data Sharing Between Threads
+
+
Use shared values to pass data between the UI and JS threads:
+
+
```typescript
+
import { useSharedValue } from "react-native-reanimated"
+
+
function App() {
+
const width = useSharedValue(100)
+
+
function myWorklet() {
+
"worklet"
+
width.value += 50
+
}
+
+
useEffect(() => {
+
console.log(width.value) // Accessible on both JS and UI threads
+
}, [])
+
}
+
```
+
+
### Running Functions on the JS Thread
+
+
Use `runOnJS` to execute functions from the UI thread, often for non-worklet functions or React state updates:
+
+
```typescript
+
import { router } from "expo-router"
+
import { Gesture } from "react-native-gesture-handler"
+
+
function App() {
+
const tap = Gesture.Tap().onEnd(() => {
+
// Worklet context
+
runOnJS(router.back)()
+
})
+
}
+
```
+
+
Ensure functions passed to `runOnJS` are defined in the JavaScript thread scope:
+
+
```typescript
+
function App() {
+
const tap = Gesture.Tap().onEnd(() => {
+
// myFunction is defined on the UI thread 🚨
+
const myFunction = () => {}
+
runOnJS(myFunction)() // 💥 Error
+
})
+
}
+
```
+
+
### Custom Worklet Runtimes
+
+
Worklets can operate in custom runtimes beyond Reanimated's default. Libraries like VisionCamera and LiveMarkdown create their own worklet environments.
+
+
Create your own worklet runtime using `createWorkletRuntime`.
+
+
## Accessibility
+
+
This section discusses how Reanimated enhances accessibility in animations, particularly through its reduced motion functionality. This feature ensures a smoother experience for users with motion sensitivities or those who prefer less movement.
+
+
The reduced motion configuration allows you to define how animations should respond to the system's reduced motion setting. For any animation, the value can be set as follows:
+
+
- `ReduceMotion.System`: Adjusts the animation based on whether the device's reduced motion accessibility setting is activated. If enabled, the animation is disabled; otherwise, it remains active.
+
- `ReduceMotion.Always`: Consistently disables the animation, regardless of the device's accessibility configuration.
+
- `ReduceMotion.Never`: Ensures that the animation remains enabled at all times.
+
+
By default, all animations are configured with `ReduceMotion.System`.
+
+
### Reduced Motion in Animations
+
+
```typescript
+
import { withDelay, withTiming } from "react-native-reanimated"
+
+
function App() {
+
sv1.value = withTiming(0, { reduceMotion: ReduceMotion.System })
+
sv2.value = withDelay(
+
1000,
+
withTiming(toValue, { duration }),
+
ReduceMotion.System
+
)
// ...
+
}
+
```
+
+
When reduced motion is enabled:
+
+
- `withSpring` and `withTiming` return the `toValue` immediately.
+
- `withDecay` returns the current value immediately, considering the clamp parameter.
+
- `withDelay` initiates the next animation immediately.
+
- `withRepeat`:
+
- If `numberOfReps` is infinite or even and the animation is reversed, then the repeated animation does not start.
+
- Otherwise, the repeated animation runs once.
+
- `withSequence` exclusively starts animations that have reduced motion disabled.
+
+
Higher-order animations pass the configuration to their children only if the children haven't been configured by the user. For example:
-
return <Animated.View style={[{ width: 100, height: 100 }, animatedStyle]} />;
+
This animation will instantaneously reach the `toValue`:
+
+
```typescript
+
import { withDelay, withTiming } from "react-native-reanimated"
+
+
function App() {
+
sv.value = withDelay(
+
1000,
+
withTiming(toValue, { duration }),
+
ReduceMotion.Always
+
)
+
// ...
+
}
+
```
+
+
This animation will execute as usual even if reduced motion is enabled on the device:
+
+
```typescript
+
import { withDelay, withTiming } from "react-native-reanimated"
+
+
function App() {
+
sv.value = withDelay(
+
1000,
+
withTiming(toValue, { duration }),
+
ReduceMotion.Never
+
)
+
// ...
+
}
+
```
+
+
And here `withTiming` will be executed as usual and without delay:
+
+
```typescript
+
import { withDelay, withTiming } from "react-native-reanimated"
+
+
function App() {
+
sv.value = withDelay(
+
1000,
+
withTiming(toValue, { duration, reduceMotion: ReduceMotion.Never }),
+
ReduceMotion.Always
+
)
+
// ...
+
}
+
```
+
+
### Reduced Motion in Layout Animations
+
+
```typescript
+
import { BounceIn } from "react-native-reanimated"
+
+
function App() {
+
const entering = BounceIn.reduceMotion(ReduceMotion.System)
+
// ...
+
}
+
```
+
+
When reduced motion is enabled:
+
+
- Entering, keyframe, and layout animations instantaneously reach their endpoints.
+
- Exiting animations and shared transitions are omitted.
+
+
### `useReducedMotion`
+
+
This hook returns a boolean indicating whether the reduced motion setting was enabled when the app started. It can be used in conjunction with other libraries or to conditionally display animations that are less intrusive.
+
+
```typescript
+
import { BounceIn } from "react-native-reanimated"
+
+
function App() {
+
const reduceMotion = useReducedMotion()
+
const entering = reduceMotion
+
? FadeIn.reduceMotion(ReduceMotion.Never)
+
: BounceIn
+
// ...
+
}
+
```
+
+
## Glossary of terms
+
+
### Animated Component
+
+
Animated components are those that can be animated using Reanimated. The library includes built-in components such as `Animated.View`, `Animated.Text`, and `Animated.ScrollView`.
+
+
```typescript
+
import Animated from 'react-native-reanimated';
+
+
function App() {
+
return (
+
<Animated.View
+
style={{
+
width: 100,
+
height: 100,
+
backgroundColor: 'violet',
+
}}
+
/>
+
);
+
}
+
```
+
+
For components not included in Reanimated, you can make their props and styles animatable by wrapping them with `createAnimatedComponent`:
+
+
```typescript
+
import Animated from "react-native-reanimated"
+
import { Circle } from "react-native-svg"
+
+
const AnimatedCircle = Animated.createAnimatedComponent(Circle)
+
```
+
+
### Shared Value
+
+
Shared values are essential for animations in Reanimated. They are defined using the `useSharedValue` hook and accessed or modified via their `.value` property.
+
+
```typescript
+
import { useSharedValue } from "react-native-reanimated"
+
+
function App() {
+
const sv = useSharedValue(0)
+
+
const handlePress = () => {
+
sv.value += 10
+
}
+
+
// rest of your glamorous code ✨
+
}
+
```
+
+
Shared values can store any type and automatically synchronize data between the JavaScript thread and the UI thread.
+
+
### Animatable Value
+
+
An animatable value is a type that can be used for animations, including numbers, strings, and arrays of numbers. Strings in specific formats like `"10deg"`, `"21%"`, or colors such as `"#ffaabb"` or `"rgba(100, 200, 100, 0.7)"` are also animatable.
+
+
### Animation Function
+
+
Animation functions define how animations should behave. Reanimated provides three built-in animation functions:
+
+
- `withSpring`: Creates spring-based animations.
+
- `withTiming`: Creates duration and easing-based animations.
+
- `withDecay`: Mimics motion with a given deceleration rate.
+
+
These can be combined with modifiers for complex animations.
+
+
### Animation Modifier
+
+
Animation modifiers customize animations. Known as higher-order animations, Reanimated includes:
+
+
- `withDelay`: Adds a delay before the animation starts.
+
- `withRepeat`: Repeats an animation a specified number of times.
+
- `withSequence`: Chains animations sequentially.
+
- `withClamp`: Limits animation boundaries to a specific range.
+
+
### Animation Object
+
+
An animation object is returned from animation functions and modifiers, containing the current state of the animation. It includes start and end conditions and an `onFrame` function for calculating each frame's state.
+
+
When passed to a shared value, it is treated as an animatable value:
+
+
```typescript
+
sv.value = withSpring(100)
+
```
+
+
### Animations in Inline Styling
+
+
Shared values can be directly used in the `style` property without `useAnimatedStyle`.
+
+
Example:
+
+
```typescript
+
function App() {
+
const width = useSharedValue(100);
+
+
return <Animated.View style={{ width }} />;
+
}
+
```
+
+
### Layout Animation Modifier
+
+
Layout animation modifiers customize layout animations. Example usage:
+
+
```typescript
+
<Animated.View entering={FadeOutLeft.duration(500).easing(Easing.ease)} />
+
```
+
+
Built-in modifiers include:
+
+
- `.duration(durationMs: number)`: Sets the animation length in milliseconds.
+
- `.easing(easingFunction: EasingFunction)`: Defines the animation curve.
+
- `.springify()`: Enables spring-based animations.
+
- `.damping(value: number)`: Controls how quickly a spring stops moving.
+
- `.withCallback(callback: (finished: boolean) => void)`: Triggers after the animation ends.
+
+
### Worklet
+
+
Worklets are short-running JavaScript functions executed on the UI thread. They can also run on the JavaScript thread like regular functions.
+
+
Code is often automatically workletized and runs on the UI thread by default:
+
+
```typescript
+
const style = useAnimatedStyle(() => {
+
console.log("Running on the UI thread")
+
return { opacity: 0.5 }
+
})
+
```
+
+
Custom worklets can be created using the `"worklet";` directive:
+
+
```typescript
+
function myWorklet() {
+
"worklet"
+
console.log("Running on the UI thread")
```
-
#### Arguments
+
Use `runOnUI` to manually execute worklets on the UI thread:
+
+
```typescript
+
function myWorklet(greeting) {
+
"worklet"
+
console.log(`${greeting} from the UI thread`)
+
}
+
+
function onPress() {
+
runOnUI(myWorklet)("Howdy")
+
}
+
```
+
+
### To Workletize
+
+
Converts a JavaScript function into an object that can be serialized and executed on the UI thread. Functions marked with `"worklet";` are automatically workletized by the Reanimated Babel plugin.
+
+
### JavaScript Thread
+
+
The JavaScript thread handles code execution in the app, serving as the primary location for React Native app code execution.
+
+
### UI Thread
+
+
The UI thread manages user interface updates and is also known as the Main thread. More information can be found in the Threading model article of the official React Native documentation.
+
+
### Reanimated Babel Plugin
+
+
This plugin automatically workletizes certain functions used with Reanimated, reducing boilerplate code. Details are available in the Reanimated Babel plugin README.
+
+
## Entering/Exiting animations
+
+
The provided content outlines a comprehensive guide for using various animations in React Native with the `react-native-reanimated` library. Below is a structured summary of the key points and features:
+
+
#### Overview
+
+
- **Library**: `react-native-reanimated`
+
- **Purpose**: To create smooth, performant animations on Android, iOS, and Web platforms.
+
- **Animations Covered**:
+
- Pinch
+
- Pinch Zoom
+
- Pinch Rotate
+
- Pinch Scale
+
- Pinch Translate
+
- Pinch X
+
- Pinch Y
+
- PinchXY
+
- PinchZoomRotate
+
- PinchZoomScale
+
- PinchZoomTranslate
+
- PinchZoomX
+
- PinchZoomY
+
- PinchZoomXY
+
- PinchZoomRotateScale
+
- PinchZoomRotateTranslate
+
- PinchZoomRotateX
+
- PinchZoomRotateY
+
- PinchZoomRotateXY
+
- PinchZoomScaleTranslate
+
- PinchZoomScaleX
+
- PinchZoomScaleY
+
- PinchZoomScaleXY
+
- PinchZoomTranslateX
+
- PinchZoomTranslateY
+
- PinchZoomTranslateXY
+
- PinchZoomRotateScaleTranslate
+
- PinchZoomRotateScaleX
+
- PinchZoomRotateScaleY
+
- PinchZoomRotateScaleXY
+
- PinchZoomRotateTranslateX
+
- PinchZoomRotateTranslateY
+
- PinchZoomRotateTranslateXY
+
- PinchZoomScaleTranslateX
+
- PinchZoomScaleTranslateY
+
- PinchZoomScaleTranslateXY
+
- PinchZoomRotateScaleTranslateX
+
- PinchZoomRotateScaleTranslateY
+
- PinchZoomRotateScaleTranslateXY
+
- Other animations like Bounce, Fade, Flip, etc.
-
- **`value`**: A number from the input range that is mapped to the output range.
+
#### Animation Configuration
-
- **`input`**: An array of numbers specifying the input range for interpolation. The values should be in increasing order.
+
##### Time-based Modifiers
-
- **`output`**: An array of color strings (e.g., `'red'`, `'#ff0000'`, `'rgba(255, 0, 0, 0.5)'`) that define the output colors. It must have at least as many points as the input range.
+
- **Function**: `withTiming`
+
- **Customization**:
+
- `.easing(easingFunction: EasingFunction)`: Defines the animation curve. Default is `Easing.inOut(Easing.quad)`.
+
- Note: These modifiers do not affect spring animations.
-
- **`colorSpace`** *(Optional)*: Specifies the color space for interpolation, either `'HSV'` or `'RGB'`. Defaults to `'RGB'`.
+
##### Spring-based Modifiers
-
- **`options`** *(Optional)*: Additional parameters for color interpolation:
+
- **Function**: `withSpring`
+
- **Customization**:
+
- `.springify()`: Enables spring-based configuration.
+
- `.damping(value: number)`: Controls how quickly the spring stops. Default is `10`.
+
- `.mass(value: number)`: Represents the weight of the spring. Lower values make animations faster. Default is `1`.
+
- `.stiffness(value: number)`: Determines bounciness. Default is `100`.
+
- `.overshootClamping(value: boolean)`: Prevents bouncing over the target position. Default is `false`.
+
- `.restDisplacementThreshold(value: number)`: Displacement threshold for snapping to the final position without oscillations. Default is `0.001`.
+
- `.restSpeedThreshold(value: number)`: Speed threshold for snapping to the final position without oscillations. Default is `2`.
+
+
##### Common Modifiers
+
+
- **Customization**:
+
- `.duration(durationMs: number)`: Length of the animation in milliseconds. Default is `300`.
+
- `.delay(durationMs: number)`: Delay before starting the animation. Default is `0`.
+
- `.randomDelay()`: Randomizes delay between `0` and provided value, defaulting to `1000ms` if not specified.
+
- `.reduceMotion(reduceMotion: ReduceMotion)`: Adjusts animation based on device's reduced motion settings.
+
- `.withInitialValues(values: StyleProps)`: Overrides initial configuration of the animation.
+
- `.withCallback(callback: (finished: boolean) => void)`: Executes a callback after the animation ends, indicating if it finished without interruptions.
-
|Options|Type|Default|Description|
-
|-|-|-|-|
-
|`gamma`|`number`|2.2|Gamma parameter used in gamma correction.|
-
|`useCorrectedHSVInterpolation`|`boolean`|true|Reduces the number of hues during interpolation by treating HSV as circular.|
+
#### Platform Compatibility
-
#### Options Explanation
+
- **Android**: Supported
+
- **iOS**: Supported
+
- **Web**: Supported
-
- **Gamma**: Colors on web/mobile are typically expressed in sRGB, a gamma-corrected color space. Operations like addition can yield incorrect results if performed directly in this non-linear space. To address this, colors are converted to linear space for interpolation and then back to sRGB. The default gamma value of 2.2 is commonly used for this conversion.
+
This guide provides developers with the tools to create and customize animations effectively across multiple platforms using `react-native-reanimated`.
-
- **Use Corrected HSV Interpolation**: This option optimizes hue transitions by selecting the shortest path on a circular spectrum (e.g., transitioning from yellow to purple via red instead of green and blue).
+
## Troubleshooting React Native Reanimated Build Issues on Windows
+
+
This guide outlines basic troubleshooting steps for resolving issues encountered when building React Native apps with Reanimated for Android devices on a Windows host machine. Common errors include:
+
+
- `Execution failed for task ':react-native-reanimated:buildCMakeDebug[x86_64]'`
+
- `Execution failed for task ':react-native-reanimated:buildCMakeRelWithDebInfo[arm64-v8a]'`
+
- `Task :react-native-reanimated:buildCMakeDebug[x86_64] FAILED`
+
- `C/C++: ninja: error: mkdir(...): No such file or directory`
+
- `C++ build system [build] failed while executing`
+
- `Picked up _JAVA_OPTIONS`
+
+
### What Not to Do
+
+
If you encounter any of the above errors, avoid these actions:
+
+
#### ❌ Avoid Disabling New Architecture
+
+
Starting from React Native 0.76, New Architecture is enabled by default. Manually disabling it in `gradle.properties` does not resolve issues and merely delays them since legacy architecture will be phased out.
+
+
#### ❌ Avoid Downgrading Android Gradle Plugin (AGP)
+
+
Do not modify the AGP version in `gradle.properties`. Use the version specified in the official app template to prevent version conflicts and unsupported features.
+
+
#### ❌ Avoid Downgrading Reanimated or Other Dependencies
+
+
Downgrading increases technical debt. Newer versions of Reanimated include bug fixes and stability improvements. Always use the latest supported version, and consider upgrading all dependencies rather than downgrading them.
+
+
#### ❌ Avoid Posting Duplicate "Same Issue" Comments
+
+
Before reporting an error, search for similar issues on platforms like GitHub or Stack Overflow. Instead of posting duplicate comments, add a reaction to the original issue to indicate its impact.
+
+
### Recommended Actions
+
+
#### ✅ Ensure Correct Environment Setup
+
+
Follow all instructions in Set Up Your Environment. Run `npx react-native doctor` to identify any problems. Restart your terminal, IDE, or computer if changes have been made.
+
+
#### ✅ Use Compatible Reanimated Version
+
+
Use the latest supported version of Reanimated based on your app setup:
+
+
- **Expo SDK**: Match major and minor versions with Expo SDK.
+
- Example: Expo SDK 52 supports `~3.16.x`. Update to the latest patch, e.g., `3.16.7`.
+
+
|Expo SDK Version|Reanimated Version|
+
|-|-|
+
|`52`|`~3.16.1`|
+
|`51`|`~3.10.1`|
+
|`50`|`~3.6.2`|
+
+
- **Expo Prebuild or React Native without Framework**: Use a version compatible with your React Native version according to the Compatibility table.
+
+
#### ✅ Use Appropriate CMake Version
+
+
Ensure you use CMake `3.22.1` or newer. Customize the version using the `CMAKE_VERSION` environment variable, e.g., `set CMAKE_VERSION=3.31.1`. If unset, default is `3.22.1`.
+
+
#### ✅ Use Appropriate Ninja Version
+
+
Use Ninja `1.12.0` or newer (latest is `1.12.1`) as older versions may not handle long paths correctly.
+
+
#### ✅ Use Compatible Android NDK Version
+
+
Match the NDK version with that used in the official app template. It should be installed automatically during app build.
+
+
#### ✅ Unset `_JAVA_OPTIONS`
+
+
Unsetting this environment variable can resolve certain errors and allow builds to pass.
+
+
#### ✅ Enable Long Paths Support in Windows Registry
+
+
Follow instructions to enable long paths support on Windows.
+
+
#### ✅ Avoid Whitespace in Project Path
+
+
Paths with spaces may cause issues. Move projects to directories without whitespace, e.g., `D:\Mobile Apps\MyAwesomeProject`.
+
+
#### ✅ Ensure Short Project Path
+
+
Avoid paths longer than 240 characters. Move or clone the project to a shorter path, e.g., `D:\AwesomeProject`.
+
+
#### ✅ Remove or Invalidate Caches
+
+
Clear compilation artifacts in directories like:
+
+
- `android\build`
+
- `android\.cxx`
+
- `android\.gradle`
+
- `node_modules\react-native-reanimated\android\build`
+
+
Invalidate Android Studio caches (File → Invalidate Caches…).
+
+
#### ⚠️ Persistent Issues
+
+
If problems persist after following these steps, submit an issue in the repository with full build logs and a minimal reproducible example.
+
+
## Compatibility Table
+
+
### Currently Supported React Native Versions (Paper)
+
+
|Version|0.63|0.64|0.65|0.66|0.67|0.68|0.69|0.70|0.71|0.72|0.73|0.74|0.75|0.76|0.77|0.78|0.79|0.80|
+
|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|
+
|3.18.0|no|no|no|no|no|no|no|no|no|no|no|no|yes|yes|yes|yes|yes|yes|
+
|3.17.4 - 3.17.5|no|no|no|no|no|no|no|no|no|no|no|no|yes|yes|yes|yes|yes|no|
+
|3.17.1 – 3.17.3|no|no|no|no|no|no|no|no|no|no|no|no|yes|yes|yes|yes|no|no|
+
|3.17.0|no|no|no|no|no|no|no|no|no|no|no|no|yes|yes|yes|no|no|no|
+
|3.16.7|no|no|no|no|no|no|no|no|no|no|no|yes|yes|yes|yes|no|no|no|
+
|3.16.0 – 3.16.6|no|no|no|no|no|no|no|no|no|no|no|yes|yes|yes|no|no|no|no|
+
|3.15.x|no|no|no|no|no|no|no|no|no|no|no|yes|yes|no|no|no|no|no|
+
|3.9.x – 3.14.x|no|no|no|no|no|no|no|no|no|no|no|yes|no|no|no|no|no|no|
+
|3.6.x – 3.8.x|no|no|no|yes|yes|yes|yes|yes|yes|yes|yes|no|no|no|no|no|no|no|
+
|3.5.x|no|no|no|yes|yes|yes|yes|yes|yes|yes|no|no|no|no|no|no|no|no|
+
|3.3.x – 3.4.x|yes|yes|yes|yes|yes|yes|yes|yes|yes|yes|no|no|no|no|no|no|no|no|
+
|3.0.x – 3.2.x|yes|yes|yes|yes|yes|yes|yes|yes|yes|no|no|no|no|no|no|no|no|no|
+
|2.14.x – 2.17.x|yes|yes|yes|yes|yes|yes|yes|yes|yes|no|no|no|no|no|no|no|no|no|
+
|2.11.x – 2.13.x|yes|yes|yes|yes|yes|yes|yes|yes|no|no|no|no|no|no|no|no|no|no|
+
|2.10.x|yes|yes|yes|yes|yes|yes|yes|no|no|no|no|no|no|no|no|no|no|no|
+
|2.5.x – 2.9.x|yes|yes|yes|yes|yes|yes|no|no|no|no|no|no|no|no|no|no|no|no|
+
|2.3.x – 2.4.x|yes|yes|yes|yes|yes|no|no|no|no|no|no|no|no|no|no|no|no|no|
+
+
**Note:** Reanimated 2 will not receive support for the newest React Native versions. To access the latest features and updates, upgrade to Reanimated 3.
+
+
### Supported React Native Versions on the New Architecture (Fabric)
+
+
To use Reanimated with the experimental New Architecture, update the package to at least version 3.0.0. Due to numerous breaking changes related to the New Architecture in each React Native version, as a rule of thumb, Reanimated supports the latest stable version of React Native.
+
+
Reanimated supports bridgeless mode.
+
+
|Version|0.63|0.64|0.65|0.66|0.67|0.68|0.69|0.70|0.71|0.72|0.73|0.74|0.75|0.76|0.77|0.78|0.79|0.80|
+
|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|
+
|3.18.0|no|no|no|no|no|no|no|no|no|no|no|no|yes|yes|yes|yes|yes|yes|
+
|3.17.4 - 3.17.5|no|no|no|no|no|no|no|no|no|no|no|no|yes|yes|yes|yes|yes|no|
+
|3.17.1 – 3.17.3|no|no|no|no|no|no|no|no|no|no|no|no|yes|yes|yes|yes|no|no|
+
|3.17.0|no|no|no|no|no|no|no|no|no|no|no|no|yes|yes|yes|no|no|no|
+
|3.16.7|no|no|no|no|no|no|no|no|no|no|no|yes|yes|yes|yes|no|no|no|
+
|3.16.0 – 3.16.6|no|no|no|no|no|no|no|no|no|no|no|yes|yes|yes|no|no|no|no|
+
|3.15.x|no|no|no|no|no|no|no|no|no|no|no|yes|yes|no|no|no|no|no|
+
|3.9.x – 3.14.x|no|no|no|no|no|no|no|no|no|no|no|yes|no|no|no|no|no|no|
+
|3.6.x – 3.8.x|no|no|no|no|no|no|no|no|no|yes|yes|no|no|no|no|no|no|no|
+
|3.1.x – 3.5.x|no|no|no|no|no|no|no|no|no|yes|no|no|no|no|no|no|no|no|
+
|3.0.x|no|no|no|no|no|no|no|no|yes|no|no|no|no|no|no|no|no|no|
+
+
## useSharedValue
+
+
`useSharedValue` is a hook that allows you to define shared values within your components.
+
+
### Reference
+
+
```typescript
+
import { useSharedValue } from "react-native-reanimated"
+
+
function App() {
+
const sv = useSharedValue(100)
+
+
// Accessing the shared value
+
console.log(sv.value)
+
+
// Modifying the shared value
+
sv.value += 50
+
}
+
```
+
+
#### Arguments
+
+
##### `initialValue`
+
+
The initial value to store in the shared value. It can be any JavaScript type such as `number`, `string`, or `boolean`, and also includes data structures like `array` and `object`.
#### Returns
-
The function returns an interpolated color in `rgba(r, g, b, a)` format within the specified output range.
+
`useSharedValue` returns a shared value initialized with the provided `initialValue`. You can access this stored data using its `value` property or through `get` and `set` methods.
+
+
##### React Compiler Support
+
+
When utilizing the React Compiler, avoid directly accessing or modifying the `value` property. Instead, use the `get` and `set` methods as they are compliant with React Compiler standards.
+
+
```typescript
+
function App() {
+
const sv = useSharedValue(100)
+
+
const animatedStyle = useAnimatedStyle(() => {
+
"worklet"
+
return { width: sv.get() * 100 }
+
})
+
+
const handlePress = () => {
+
sv.set((value) => value + 1)
+
}
+
}
+
```
### Remarks
-
- The function operates similarly to the `interpolate` function but specifically outputs a color string in `rgba(r, g, b, a)` notation.
+
- Avoid reading or modifying the shared value during a component's render. Accessing the `value` property or using `get`/`set` methods is considered a side-effect, which violates React's Rules of Render.
+
+
- Changes to `sv.value` will update styles and synchronize the shared value across threads without triggering a typical React re-render since it's a plain JavaScript object.
+
+
- Reading `sv.value` on the JavaScript thread may block until the value is fetched from the UI thread. This can be negligible, but if the UI thread is busy or values are read multiple times, synchronization delays might increase.
+
+
- Changes to `sv.value` occur synchronously on the UI thread, while updates on the JavaScript thread are asynchronous. Thus, logging `value` immediately after a change will show the previous value.
+
+
```typescript
+
function App() {
+
const sv = useSharedValue(100) // initially set to 100
+
+
sv.value += 50 // modifying the shared value
+
+
console.log(sv.value) // logs 100 due to asynchronous update on JS thread
+
}
+
```
+
+
- Avoid destructuring assignment with shared values. While valid in JavaScript, it prevents Reanimated from maintaining reactivity.
+
+
```typescript
+
function App() {
+
let { value } = sv // avoid this pattern
+
+
console.log(value) // reading is fine
+
+
value += 50 // does not update styles
+
}
+
```
+
+
- When storing objects in a shared value, ensure to reassign the entire object rather than modifying its properties individually.
+
+
```typescript
+
function App() {
+
const sv = useSharedValue({ x: 0, y: 0 })
+
+
sv.value.x = 50 // loses reactivity
+
+
sv.value = { x: 50, y: 0 } // correct approach
+
}
+
```
+
+
- For large arrays or complex objects in a shared value, use the `.modify` method to alter the existing value without creating a new one.
+
+
```typescript
+
function App() {
+
const sv = useSharedValue([1, 2, 3])
+
+
sv.value.push(1000) // loses reactivity
+
+
sv.value = [...sv.value, 1000] // creates a new copy
+
+
sv.modify((value) => {
+
"worklet"
+
value.push(1000) // correct approach
+
return value
+
})
+
}
+
```
### Platform Compatibility
···
|-|-|-|
|✅|✅|✅|
-
This function is versatile and compatible across major platforms, making it ideal for cross-platform applications.
+
## Contributing
+
+
Thank you for considering contributing to Reanimated. Contributions can range from triaging issues and enhancing documentation to reviewing Pull Requests and submitting code changes.
+
+
### Ways to Contribute
+
+
1. **Handling Open Issues**: Assist by providing detailed descriptions and reproducible examples for existing issues, which helps other contributors understand and address them more efficiently.
+
+
1. **Documentation Assistance**: Improve the documentation by correcting spelling and grammar or expanding explanations. You can also help update outdated pages from Reanimated v2 to the current version. For significant changes, edit locally using Docusaurus and GitHub Pages.
+
+
1. **Reviewing Pull Requests**: Review submitted Pull Requests to identify potential issues or bugs that may have been overlooked, ensuring high-quality contributions.
+
+
1. **Code Contributions**: Submit code through Pull Requests to address issues, fix bugs, or introduce new features. Beginners can start with "good first issue" tasks on GitHub.
+
+
#### Repository Structure
+
+
The Reanimated repository is organized as follows:
+
+
```
+
├── apps
+
│ ├── common-app // Shared source for example apps
+
│ ├── paper-example // React Native app using Old Architecture
+
│ ├── fabric-example // React Native app using New Architecture
+
│ ├── macos-example // React Native for MacOS wrapper
+
│ ├── next-example // Next.js wrapper
+
│ ├── tvos-example // React Native for TVOS wrapper
+
│ └── web-example // React Native for Web wrapper
+
└── packages
+
├── docs-reanimated // Documentation source
+
├── eslint-plugin-reanimated // ESLint plugin source
+
└── react-native-reanimated
+
├── android // Android native code
+
├── apple // iOS native code
+
├── Common // Shared C++ code
+
├── scripts // CI pipeline scripts
+
├── src // Reanimated JS source
+
└── plugin // Babel plugin source
+
```
+
+
### Handling Open Issues
+
+
Providing detailed descriptions and reproducible examples for issues can significantly aid other contributors. Ensure that issues include:
+
+
- A cloneable repository.
+
- Clear reproduction steps.
+
- Comprehensive descriptions.
+
- Relevant stack traces.
+
+
If these details are missing, consider asking the issue owner or providing them yourself to facilitate quicker resolutions.
+
+
### Documentation Assistance
+
+
Improving documentation is a straightforward way to contribute. The Reanimated docs use Docusaurus and GitHub Pages. For minor edits, click **Edit this page** at the bottom of most pages. For more complex changes:
+
+
1. Clone `react-native-reanimated`.
+
1. Navigate to `packages/docs-reanimated`.
+
1. Run `yarn && yarn start` to preview changes locally.
+
+
#### Documentation Structure
+
+
Maintain a consistent structure for clarity and ease of navigation:
+
+
1. **Introduction**: Briefly describe the feature.
+
1. **Reference**: Provide simple usage examples with type definitions.
+
1. **Arguments**: Detail accepted arguments.
+
1. **Returns**: Explain returned values.
+
1. **Example**: Include videos, GIFs, or interactive demos in both light and dark modes.
+
1. **Remarks**: Highlight non-obvious details like platform-specific quirks.
+
1. **Platform Compatibility**: Specify supported platforms.
+
+
#### Writing Style Guide
+
+
- Use active voice for clarity (e.g., "The function receives the arguments").
+
- Write short, clear sentences to aid comprehension.
+
- Organize information into lists for better readability.
+
- Avoid acronyms unless globally recognized (e.g., UI, API).
+
- Use contractions for a conversational tone.
+
+
#### Embedding Interactive Examples
+
+
Use the `InteractiveExample` component with `src` and `component` props to create engaging examples. For videos:
+
+
```typescript
+
import AnimatedKeyboardSrc from '!!raw-loader!@site/src/examples/AnimatedKeyboard';
+
+
<InteractiveExample
+
src={AnimatedKeyboardSrc}
+
component={
+
<ThemedVideo
+
center
+
width={300}
+
sources={{
+
light: '/recordings/useAnimatedKeyboard_light.mov',
+
dark: '/recordings/useAnimatedKeyboard_dark.mov',
+
}}
+
/>
+
}
+
/>;
+
```
+
+
For interactive components:
+
+
```typescript
+
import DecayTrain from '@site/src/examples/DecayTrain';
+
import DecayTrainSrc from '!!raw-loader!@site/src/examples/DecayTrain';
+
+
<InteractiveExample
+
src={DecayTrainSrc}
+
component={<DecayTrain />}
+
label="Grab and drag the train"
+
/>;
+
```
+
+
### Contributing Code
+
+
Submit Pull Requests to address issues or introduce new features. Start with "good first issue" tasks if you're new to open-source contributions.
+
+
#### Working with Android
+
+
1. Install dependencies: `yarn && yarn build`.
+
1. Navigate to `apps/paper-example` and run `yarn start`.
+
1. Open the project in Android Studio at `react-native-reanimated/apps/paper-example/android`.
+
+
#### Working with iOS
+
+
1. Install dependencies: `yarn && yarn build`.
+
1. Run `cd apps/paper-example/ios && bundle install && bundle exec pod install`.
+
1. Start Metro bundler: `cd apps/paper-example && yarn start`.
+
1. Open the project in Xcode at `react-native-reanimated/apps/paper-example/ios/ReanimatedExample.xcworkspace`.
+
+
#### Preparing a Pull Request
+
+
When ready, open a Pull Request using the provided template:
+
+
1. **Summary**: Link relevant issues and describe your changes.
+
1. **Test Plan**: Provide instructions for testing, including code from `EmptyExample` if applicable.
+
+
#### Testing Changes Locally
+
+
To test changes in your project, create a patch with `git diff` or point to a specific commit in `package.json`.
+
+
Thank you for contributing! 🎉
+
+
## Debugging worklets
+
+
### Overview
+
+
This document provides guidance on debugging Reanimated v2 worklets within React Native applications. Due to Reanimated's unique architecture and use of a secondary JavaScript runtime, traditional debugging methods may not function as expected. This article outlines compatible tools and their limitations.
+
+
#### React Native Debugging Tools
+
+
The following tools have been evaluated for compatibility with React Native apps using the Reanimated library:
+
+
- **Chrome Debugger (React Native Debugger):** Utilizes a web worker in your browser to execute app JavaScript code, supporting all available runtimes in React Native.
+
+
- **Chrome DevTools:** Connects to a remote JavaScript runtime, allowing code execution on the device. Note: Not compatible with JSC.
+
+
- **Flipper (Hermes debugger):** Facilitates using Chrome DevTools and offers additional UI inspection tools.
+
+
- **Safari DevTools:** Available only for iOS devices running JSC, similar in functionality to Chrome DevTools by connecting to a remote runtime.
+
+
- **React Developer Tools:** A standalone app for debugging UI through an inspector, monitoring performance, and profiling the application.
+
+
#### JS Context vs. UI Context
+
+
Understanding the distinction between the JavaScript (JS) context and the User Interface (UI) context is crucial. Debugging the regular JS context remains unchanged with Reanimated; however, debugging the UI context specific to Reanimated can be challenging.
+
+
#### Debugging Web Apps
+
+
For web applications, standard browser tools or any preferred debugging tools can be used without issues when employing Reanimated on the web.
+
+
### Compatibility Summary
+
+
|Tool|Platform|JSC|Hermes|V8|
+
|-|-|-|-|-|
+
|Chrome Debugger|Android|⚛️ ✅¹|⚛️ ✅¹|⚛️ ✅¹|
+
||iOS|⚛️ ✅¹|⚛️ ✅¹|N/A|
+
|Chrome DevTools|Android|N/A|⚛️ ✅²|⚛️|
+
||iOS|N/A|⚛️ ✅²|N/A|
+
|Flipper (Hermes debugger)|Android|N/A|⚛️ ✅²|⚛️|
+
||iOS|N/A|⚛️ ✅²|N/A|
+
|Safari DevTools|Android|N/A|N/A|N/A|
+
||iOS|⚛️ ✅|N/A|N/A|
+
|React Developer Tools|Android|⚛️|⚛️|⚛️|
+
||iOS|⚛️|⚛️|N/A|
+
+
¹ - Functions use web implementations, running worklets on the JS thread. Measure and Layout Animations are unavailable. ² - Experimental feature.
+
+
#### Legend
+
+
- ⚛️ ✅: Special features for React Native apps using Reanimated
+
- ⚛️: Standard functionality with no worklet debugging available
+
- N/A: Not applicable in React Native apps
+
+
**Note:** Console logs will always appear in the primary JS runtime as `console.log` on the UI runtime is a wrapper around the JS runtime's function.
+
+
### Tool-Specific Details
+
+
#### Chrome Debugger
+
+
|Platform|JSC|Hermes|V8|
+
|-|-|-|-|
+
|Android|⚛️ ✅|⚛️ ✅|⚛️ ✅|
+
|iOS|⚛️ ✅|⚛️ ✅|N/A|
+
+
**Summary:** Functions use web implementations, running on the JS thread. Measure and Layout Animations are unavailable.
+
+
#### Chrome DevTools
+
+
|Platform|JSC|Hermes|V8|
+
|-|-|-|-|
+
|Android|N/A|⚛️ ✅²|⚛️|
+
|iOS|N/A|⚛️ ✅²|N/A|
+
+
**Summary:** Both contexts can be debugged. This is an experimental feature.
+
+
#### Flipper (Hermes Debugger)
+
+
|Platform|JSC|Hermes|V8|
+
|-|-|-|-|
+
|Android|N/A|⚛️ ✅²|⚛️|
+
|iOS|N/A|⚛️ ✅²|N/A|
+
+
**Summary:** Both contexts can be debugged. This is an experimental feature.
+
+
#### Safari DevTools
+
+
|Platform|JSC|Hermes|V8|
+
|-|-|-|-|
+
|Android|N/A|N/A|N/A|
+
|iOS|⚛️ ✅|N/A|N/A|
+
+
**Summary:** Available only on iOS devices with the JSC engine. Worklet debugging is supported.
+
+
#### React Developer Tools
+
+
|Platform|JSC|Hermes|V8|
+
|-|-|-|-|
+
|Android|⚛️|⚛️|⚛️|
+
|iOS|⚛️|⚛️|N/A|
+
+
**Summary:** Functions as expected, with profiler and layout inspector available.
+
+
#### Additional Notes
+
+
- **Console Logs:** Always appear in the primary JS runtime.
+
+
- **Known Issues:** Include reload failures, breakpoint issues on iOS, unresponsive consoles without animations, and more. These do not affect release builds or debug builds where the debugger is disconnected during a reload.
+
+
*Efforts are ongoing to enhance debugging experiences with Chrome DevTools and Flipper on Hermes.*
+59 -41
out/llms-full-react-native.txt
···
With an understanding of how to navigate these guides, it's time to explore the foundation of React Native: Native Components.
-
## Animated Library Overview
+
## Animated
The `Animated` library is designed for creating fluid, powerful animations that are easy to build and maintain. It emphasizes declarative relationships between inputs and outputs, configurable transforms, and control over animation execution through `start`/`stop` methods.
···
- `hidesWhenStopped` (iOS)
- `size`
-
## Button Component
+
## Button
The Button component is designed to render consistently across different platforms, offering a basic level of customization. If the default appearance does not meet your needs, consider creating a custom button using Pressable. For guidance, refer to the source code of the Button component.
···
||- false|||
This table summarizes the properties available for the Button component, detailing their purpose and default values where applicable.
+
+
## Image
To integrate image handling capabilities in your React Native application, you can utilize the `<Image />` component along with various methods and properties provided for efficient image management. Below is an overview of how to use these features effectively:
···
For events with capture equivalents, the gesture state is updated once in the capture phase and can be used in the bubble phase. Be cautious with `onStartShould*` callbacks; they only reflect updated `gestureState` for start/end events that bubble/capture to the Node. Once a node becomes the responder, every start/end event updates the `gestureState`. Note that `numberActiveTouches` may not always be accurate unless you are the responder.
-
## Installing Dependencies
+
## Installing dependencies
To develop a React Native app, ensure you have Node, Watchman, the React Native CLI, a JDK, and Android Studio installed. While any editor can be used for development, Android Studio is necessary for setting up the Android build environment.
···
- For integrating React Native into an existing app, refer to the Integration guide.
- To learn more about React Native, explore the Introduction to React Native.
-
## ImageBackground Component Overview
+
## ImageBackground
The `<ImageBackground>` component is designed for developers who are accustomed to using `background-image` in web development. It functions similarly to the `<Image>` component, allowing you to layer additional content on top of an image.
···
|-|-|
|number|`0`|
-
## Modal Component
+
## Modal
The Modal component provides a straightforward method to display content above an enclosing view.
···
|-|-|
|bool|`true`|
+
## Key Concepts
+
To integrate React Native into an existing iOS application, follow these steps carefully. This guide assumes you have a basic understanding of both iOS development using Xcode and JavaScript/React Native.
#### Prerequisites
···
|radius|number|No|Sets the radius of the ripple effect.|
|foreground|boolean|No|If true, adds the ripple effect to the view's foreground instead of the background. Useful when child views have their own backgrounds or images are displayed, preventing the ripple from being obscured.|
-
## RefreshControl Component
+
## RefreshControl
The `RefreshControl` component is designed to be used within a ScrollView or ListView, providing pull-to-refresh functionality. When the scroll position (`scrollY`) reaches zero and the user swipes down, an `onRefresh` event is triggered.
···
> **Deprecated Notice:** The support for TV devices has been transitioned to a separate repository named "React Native for TV." For detailed guidance on projects targeting Apple TV or Android TV, please refer to the *README* file within that repository.
+
## ScrollView
+
The provided documentation outlines various properties and methods associated with a ScrollView component, likely from a mobile development framework such as React Native. Below is a summary of the key features:
#### Properties
···
Here, `"providesModuleNodeModules"` is a list of modules added to the Haste module search path, and `"platforms"` specifies valid platform suffixes.
-
## StatusBar Component
+
## StatusBar
The `StatusBar` component manages the app's status bar, which is typically located at the top of the screen. It displays information such as time, network status, battery level, and other status icons.
···
|`'light-content'`|string|White texts and icons.|
|`'dark-content'`|string|Dark texts and icons (requires API>=23 on Android).|
-
## Enabling USB Debugging on Android Devices
+
## 1. Enable Debugging over USB
Most Android devices restrict app installations to those downloaded from Google Play by default. To install apps during development, enable USB Debugging on your device.
···
This guide covers enabling USB debugging, setting up an Android device for React Native development, connecting to the development server via USB or Wi-Fi, and preparing your app for production release. Follow these steps to streamline your development workflow.
-
## Switch Component
+
## Switch
The `Switch` component renders a boolean input and functions as a controlled component. It necessitates an `onValueChange` callback to update its `value` prop, ensuring that user interactions are accurately reflected in the UI. Without updating the `value` prop, the component will persistently display the initially supplied value.
···
- **Description**: Determines the state of the switch. If set to `true`, the switch is on; otherwise, it's off. The default value is `false`.
- **Type**: `bool`
-
## Fast Refresh in React Native
+
## Fast Refresh
Fast Refresh is a feature in React Native that provides near-instant feedback when changes are made to your React components. By default, this feature is enabled and can be toggled through the "Enable Fast Refresh" option in the React Native Dev Menu. With it activated, most edits should become visible within seconds.
···
This behavior can lead to unexpected results, such as an empty-array `useEffect` running once during Fast Refresh. Writing resilient code for occasional `useEffect` re-runs is beneficial and aligns with best practices, facilitating future dependency additions.
-
## Metro Configuration in React Native
+
## Metro
React Native utilizes Metro to compile JavaScript code and manage assets. Below are guidelines for configuring Metro within your project.
···
- Visit the [Metro website](https://metrobundler.dev/docs/configuration) for more information.
- Watch the "Metro & React Native DevX" talk at App.js 2023 for insights into Metro's role in React Native development.
-
## Using Libraries in React Native
+
## Using Libraries
React Native offers built-in Core Components and APIs, but you can also leverage a vast community of developers to find additional libraries that extend your app's functionality.
···
```shell
npm install @react-native-community/netinfo@^2.0.0
```
+
+
## Text
Here's a structured overview and explanation of the `Text` component in React Native, focusing on its properties and usage:
···
The `Text` component in React Native is highly customizable, supporting various styling and accessibility options. Understanding its properties allows developers to create rich, interactive text elements tailored to specific application needs.
+
## TextInput
+
Here is a structured overview of the properties, methods, and known issues related to the `TextInput` component in React Native:
#### Properties
···
This overview provides a comprehensive guide to using and understanding the `TextInput` component in React Native, including its properties, methods, and known issues.
-
## TouchableHighlight Component
+
## TouchableHighlight
> For a more robust and future-proof approach to handling touch-based input, consider using the Pressable API.
···
- **testOnly\_pressed**: Useful for snapshot tests.
- Type: bool
-
## TouchableOpacity Component
+
## TouchableOpacity
> For a more comprehensive and future-proof approach to handling touch-based input, consider using the Pressable API.
···
- **Platform**: Android
- Description: Identifies the next focusable view when navigating up using a TV remote, as detailed in the View component documentation.
-
## Upgrading React Native Versions
+
## Upgrading to new versions
Upgrading to newer versions of React Native provides access to additional APIs, views, developer tools, and other enhancements. Although the process requires some effort, we aim to make it as straightforward as possible.
···
|`testID`|Used to locate this view in end-to-end tests.|string|
|`touchSoundDisabled` (Android)|If set to true, prevents the system sound from playing on touch.|Boolean|
-
## Text
+
## View
#### Accessibility Properties
···
This documentation provides comprehensive details on how to configure various aspects of a `View`, focusing on accessibility, layout, interaction, and identification.
-
## Style in React Native
+
## Style
In React Native, styling your application is done using JavaScript. Core components accept a `style` prop, which typically mirrors CSS conventions but uses camel casing for property names (e.g., `backgroundColor` instead of `background-color`).
···
To occupy a specific portion of the screen without using the `flex` layout, you can use **percentage values** in the component's style. Like flex dimensions, percentage dimensions require that the parent has defined dimensions.
-
## DrawerLayoutAndroid Component
+
## DrawerLayoutAndroid
The `DrawerLayoutAndroid` is a React component specifically designed for Android platforms. It encapsulates the platform's native `DrawerLayout`. This layout typically serves as a navigation drawer, which can be rendered using the `renderNavigationView` prop. The main content of your application resides within its direct children.
···
Opens the navigation drawer.
-
## Flexbox Layout in React Native
+
## Layout with Flexbox
Flexbox provides a consistent way to design layouts across different screen sizes. In React Native, it shares similarities with CSS on the web but has specific differences such as default values for properties like `flexDirection`, `alignContent`, and `flexShrink`.
···
- **react-native#18997**: Does not support multiline `TextInput`.
- **react-native#20157**: Incompatible with a bottom tab bar.
-
## SafeAreaView Overview
+
## SafeAreaView
The `SafeAreaView` component ensures that content is displayed within the safe area boundaries of a device. It's specifically designed for iOS devices running version 11 or later.
···
`SafeAreaView` inherits all View Props. Note that any padding specified in styles applied to a `SafeAreaView` will be ignored, as the component uses its own padding logic. This can lead to different results across platforms. For more details, refer to issue #22211.
-
## Image Style Properties
+
## Image Style Props
### Examples
···
|-|
|color|
-
## Shadow Properties in React Native
+
## Shadow Props
- TypeScript
- JavaScript
···
|-|
|number|
-
## Text Style Properties
+
## Text Style Props
### Example
···
- `'all'`
- **Default**: `none`
-
## View Style Properties
+
## View Style Props
### Example
···
- `boxShadow`
-
## Handling Touches in React Native
+
## Handling Touches
Users primarily interact with mobile applications through touch gestures such as tapping buttons, scrolling lists, or zooming maps. React Native offers components to manage common gestures and a comprehensive gesture responder system for advanced recognition. The `Button` component is particularly useful for basic interactions.
···
React Navigation also offers packages for different navigators, such as tabs and drawers, enabling various navigation patterns in your app. For a comprehensive introduction to React Navigation, refer to the React Navigation Getting Started Guide.
-
## Troubleshooting Guide for React Native Setup
+
## Troubleshooting
This guide addresses common issues encountered during the setup of React Native. If you face an issue not listed here, consider searching for it on GitHub.
···
Having covered React and React Native’s Core Components, let's explore handling `<TextInput>` further.
-
## Core Components and APIs in React Native
+
## Core Components and APIs
React Native offers a variety of built-in core components that can be utilized directly within your application. These components are accessible via the navigation sidebar or the top menu for narrower screens.
···
export default MyScrollView;
```
-
## Using List Views in React Native
+
## Using List Views
React Native offers several components designed for presenting lists of data efficiently. The primary choices are `FlatList` and `SectionList`.
···
**Pro tip:** Configure your Web bundler to ignore `.native.js` extensions to avoid including unused code in production, reducing bundle size.
+
## Accessibility
+
#### Overview of Accessibility Features in React Native
React Native provides several accessibility features that help developers create applications usable by everyone, including people with disabilities. These features are crucial for ensuring inclusivity and compliance with accessibility standards like WCAG (Web Content Accessibility Guidelines).
···
- Safari Developer Tools (Direct JSC Debugging)
- Remote JavaScript Debugging (Removed)
-
## Testing Guide for Code Quality Assurance
+
## Testing
As your codebase grows, small errors can lead to significant failures. Bugs negatively impact user experience and business outcomes. To prevent fragile programming, testing is essential before releasing software.
···
|userInterfaceStyleiOS|string|Interface style for the alert, set to `light` or `dark`, otherwise defaults to system style.|
|onDismissAndroid|function|Callback fired when the alert is dismissed.|
-
## Optimizing JavaScript Loading
+
## Optimizing JavaScript loading
Parsing and executing JavaScript code requires both memory and time. As applications grow, it becomes beneficial to delay loading code until it's needed for the first time. React Native includes standard optimizations by default, but additional techniques can further enhance app efficiency. For very large apps, advanced automatic optimizations are available, though they come with tradeoffs.
···
This structure is generated using the value `all` for `codegenConfig.type`. Use `modules` to exclude `react/renderer/components/`, and `components` to exclude other files.
-
## Codegen CLI Overview
+
## The Codegen CLI
The **Codegen** CLI simplifies running tasks by eliminating the need to remember complex commands or manually execute scripts. It facilitates executing `@react-native/codegen` for React Native projects with ease.
···
By following these steps, you can streamline your development process and ensure that your library remains compatible with various React Native versions.
-
## Introduction
+
## Native Platform
### Overview
···
**Previous:** The Codegen CLI\
**Next:** Android and iOS
-
## BackHandler API Overview
+
## BackHandler
The **BackHandler** API is designed for Android devices to manage hardware button presses related to back navigation. It allows developers to register event listeners and control the application's response to these events.
···
```typescript
static exitApp();
```
+
+
## Native Modules
To implement a cross-platform `localStorage` solution using React Native's TurboModule system, you need to set up both Android and iOS platforms. Below is a step-by-step guide based on the provided instructions:
···
```
This setup provides a consistent `localStorage` API across both platforms using React Native's TurboModule system.
+
+
## Cross-Platform Native Modules (C++)
Creating a cross-platform native module using C++ is an efficient way to share platform-agnostic code between Android and iOS. This guide walks through the process of creating a pure C++ Turbo Native Module, which allows you to write your logic once and reuse it across platforms.
···
You've successfully created a C++ Turbo Native Module that works on both Android and iOS. This setup allows you to write platform-agnostic code in C++, reducing redundancy and improving maintainability across platforms.
+
## Native Components
+
To create a native web view component in React Native, you need to implement platform-specific code for both Android and iOS. Below is a step-by-step guide on how to achieve this:
#### Step 1: Set Up Your Project
···
Congratulations! You've published your first React Native library.
-
## ToastAndroid API in React Native
+
## ToastAndroid
The `ToastAndroid` API in React Native provides access to Android's native toast notifications. It offers methods for displaying short or long messages with optional positioning and offset adjustments.
···
If native usage is required, include the library's headers by going to your project file, selecting `Build Settings`, and searching for `Header Search Paths`. Add the path to your library. (Previously recommended using `recursive` is now discouraged due to potential build failures, especially with CocoaPods.)
-
## Running on Simulator
+
## Running On Simulator
### Starting the Simulator
···
**Example:**
-
## Appearance Module
+
## Appearance
The `Appearance` module provides information about the user's appearance preferences, such as their preferred color scheme (light or dark).
···
> **Note**: Ensure any `View` intended to receive accessibility focus has `accessible={true}`.
-
## AppState Overview
+
## AppState
The `AppState` module provides information about whether an application is in the foreground or background and notifies you of any state changes. It's particularly useful for determining how to handle push notifications based on the app's current state.
···
A line with `hairlineWidth` might not be visible if your simulator is downscaled.
-
## Dimensions in React Native
+
## Dimensions
`useWindowDimensions` is the recommended API for React components, as it updates automatically with changes to the window's dimensions. This aligns well with the React paradigm.
···
|scale|number|
|fontScale|number|
-
## Props in React Native
+
## Props
In React Native, most components are customizable through parameters known as `props`, short for properties. These allow developers to tailor component behavior and appearance.
···
Register the value to the profile name on the systrace timeline.
-
## Easing Module
+
## Easing
The `Easing` module provides a collection of common easing functions used to create physically believable motion in animations, particularly with `Animated.timing()`.
···
Indicates the width in pixels of the window or screen that your application occupies.
-
## Keyboard Module
+
## Keyboard
The `Keyboard` module provides functionality for controlling and responding to keyboard events in your application. It allows you to listen for native keyboard notifications, dismiss the keyboard, and synchronize layout animations with keyboard movements.