Get current value of Animated.Value, React-native

Solution 1:

I find out, how to get a value:

this.state.translateAnim.addListener(({value}) => this._value = value);

EDIT

to log a value I do the following:

console.log(this.state.translateAnim._value)

Solution 2:

This also works for me...

const headerHeight = new Animated.Value(0);

After some manipulation....

console.log(headerHeight.__getValue())

It feels hackish but it gets the job done...

Solution 3:

For the people with typescript.

console.log((this.state.translateAnim as any)._value);

It worked for me to full tsc as any.

Solution 4:

edit: CAUTION - MAY CAUSE SEVERE PERFORMANCE ISSUES. I have not been able to figure out why, but if you use this for 30+ simultaneous animations your framerate will slow to a crawl. It seems like it must be a bug in react-native with Animated.Value addListener as I don't see anything wrong with my code, it only sets a listener which sets a ref which should be instantaneous.

Here's a hook I came up with to do it without resorting to accessing private internal values.

/**
 * Since there's no (official) way to read an Animated.Value synchronously this is the best solution I could come up with
 * to have access to an up-to-date copy of the latest value without sacrificing performance.
 * 
 * @param animatedValue the Animated.Value to track
 * @param initial Optional initial value if you know it to initialize the latest value ref before the animated value listener fires for the first time
 *
 * returns a ref with the latest value of the Animated.Value and a boolean ref indicating if a value has been received yet
 */
const useAnimatedLatestValueRef = (animatedValue: Animated.Value, initial?: number) => {
    //If we're given an initial value then we can pretend we've received a value from the listener already
    const latestValueRef = useRef(initial ?? 0)
    const initialized = useRef(typeof initial == "number")

    useEffect(() => {
        const id = animatedValue.addListener((v) => {
            //Store the latest animated value
            latestValueRef.current = v.value
            //Indicate that we've recieved a value
            initialized.current = true
        })

        //Return a deregister function to clean up
        return () => animatedValue.removeListener(id)

        //Note that the behavior here isn't 100% correct if the animatedValue changes -- the returned ref
        //may refer to the previous animatedValue's latest value until the new listener returns a value
    }, [animatedValue])


    return [latestValueRef, initialized] as const
}