import React, { memo, useCallback, useEffect, useRef, useState } from 'react'; import { Animated, LayoutChangeEvent, StyleProp, View, ViewStyle, } from 'react-native'; import { animateLoop } from './helpers'; import { styles } from './styles'; type PlaceholderProps = { animated?: boolean; style?: StyleProp; }; const Placeholder = ({ animated = false, style }: PlaceholderProps) => { const loopAnimation = useRef(null); const [width, setWidth] = useState(0); const animatedValue = useRef(new Animated.Value(0)).current; const stopLoop = useCallback(() => { if (loopAnimation.current) { loopAnimation.current.stop(); loopAnimation.current = null; } animatedValue.stopAnimation(); animatedValue.setValue(0); }, [animatedValue]); useEffect(() => { stopLoop(); if (width > 0 && animated === true) { loopAnimation.current = animateLoop({ variable: animatedValue, toValue: 1, }); } return stopLoop; }, [animated, animatedValue, stopLoop, width]); const handleLayout = useCallback((event: LayoutChangeEvent) => { const nextWidth = event.nativeEvent.layout.width; setWidth((currentWidth) => currentWidth === nextWidth ? currentWidth : nextWidth ); }, []); return ( {animated === true && ( )} ); }; export default memo(Placeholder);