react-tweenful icon indicating copy to clipboard operation
react-tweenful copied to clipboard

Animation is run at every re-render

Open Kyliathy opened this issue 5 years ago • 2 comments

Hey :). I'm using functional components and useState. Simply changing the value of a textbox (via the function provided by setState) will cause the animation to be re-run. Maybe I'm missing something :).

Kyliathy avatar Apr 20 '20 23:04 Kyliathy

Can you share your piece of code because if you are using hooks so we have to maintain some rules in hooks..

vishalkumarsinghvi avatar May 10 '20 06:05 vishalkumarsinghvi

@Kyliathy @vishalkumarsinghvi

I faced similar situation and I found the cause of the problem.

The old code cause the animation to start again every time render is called:

    render() {
       let animate = { left: ['0px', '250px']}
        return (
            <Tweenful.div
                className="tween-box row ml-2 mb-2 mr-2 mt-2"
                duration={1500}
                easing={elastic(1, 0.25)}
                style={{ position: 'relative' }}
                animate={animate}>
                <video id="video-elem" controls width="320" height="240"></video>
            </Tweenful.div>
        )
    }

What is going on is that the animate object is created every time render is called, so the animation passed to Tweenful.div is different object, this cause Teenful to start animation again.

One working solution is to put the animate object in component state, like following:

    constructor() {
        super();
        this.state = {
            animate: { left: ['0px', '300px'] }
        }
    }

And in your render function, use the animate object in state, it will be the same reference (object) across different render calls

            <Tweenful.div
                className="tween-box row ml-2 mb-2 mr-2 mt-2"
                duration={1500}
                easing={elastic(1, 0.25)}
                style={{ position: 'relative' }}
                animate={this.state.animate}>
                <video id="video-elem" controls width="320" height="240"></video>
            </Tweenful.div>

Then it just works fine.

roackb2 avatar Sep 07 '20 04:09 roackb2