javascriptreactjsreact-spring

How to stop react-spring looping animation


I have a pulsing simple Timer. I want to stop pulsing animation when the time hit "0". I am kinda new to the react-spring if anyone know how to do this please help.

const Timer = ({time = 0}) => {
    const [timer, setTimer] = useState(time);

    const props = useSpring({
        config: {duration: 1000},
        from: { scale: 1 },
        to: {scale: 1.1},
        loop: timer > 0,
    });

    useEffect(() => {
        if (!timer) return;

        const intervalId = setInterval(() => {
            setTimer(timer - 1);
        }, 1000);

        return () => clearInterval(intervalId);
    }, [timer])

    return (<animated.div style={props} className={'timer-main'}>
        { timer }
    </animated.div>)
}

Solution

  • const Timer = ({time = 0}) => {
    const [timer, setTimer] = useState(time);
    const [isCancel, setIsCancel] = useState(false);
    
    const props = useSpring({
        config: {duration: 1000},
        from: { scale: 1 },
        to: {scale: 1.1},
        loop: timer > 0,
        cancel: isCancel
    });
    
    useEffect(() => {
        if (!timer) return;
    
        const intervalId = setInterval(() => {
            const newTime = timer - 1;
    
            setTimer(newTime);
            
            if(newTime === 0){
              setIsCancel(true)
            }
        }, 1000);
    
        return () => clearInterval(intervalId);
    }, [timer])
    
    return (<animated.div style={props} className={'timer-main'}>
        { timer }
    </animated.div>)
    }
    

    There is cancel property in spring and it stops animation with boolean.