Last active
August 14, 2025 10:16
-
-
Save byteab/2187435e3ea8d6dd581eec672ed1cf7f to your computer and use it in GitHub Desktop.
Achieve apple like spring motions with react native reanimated 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { withSpring } from 'react-native-reanimated' | |
| export interface AppleSpringConfig { | |
| duration?: number | |
| bounciness?: number | |
| velocity?: number | |
| overshootClamping?: boolean | |
| restSpeedThreshold?: number | |
| restDisplacementThreshold?: number | |
| } | |
| /** mimics apple spring with bounce */ | |
| export function withBounce( | |
| toValue: number, | |
| config: AppleSpringConfig, | |
| callback?: (finished?: boolean) => void | |
| ) { | |
| 'worklet' | |
| const { | |
| duration = 0.5, | |
| bounciness = 0.0, | |
| velocity = 0, | |
| overshootClamping = false, | |
| restSpeedThreshold = 0.001, | |
| restDisplacementThreshold = 0.001, | |
| } = config | |
| const baseMass = 1 | |
| const targetSettlingTime = duration | |
| const stiffness = Math.max(10, 200 * (0.5 / targetSettlingTime) ** 2) | |
| const criticalDamping = 2 * Math.sqrt(baseMass * stiffness) | |
| const dampingRatio = Math.max(0.1, 1 - bounciness * 0.9) | |
| const damping = criticalDamping * dampingRatio | |
| const mass = baseMass * Math.max(0.5, targetSettlingTime / 0.5) | |
| return withSpring( | |
| toValue, | |
| { | |
| damping: Math.round(damping * 100) / 100, | |
| mass: Math.round(mass * 100) / 100, | |
| stiffness: Math.round(stiffness * 100) / 100, | |
| velocity, | |
| overshootClamping, | |
| restSpeedThreshold, | |
| restDisplacementThreshold, | |
| }, | |
| callback | |
| ) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment