beekai-oss / react-simple-animate

🎯 React UI animation made easy
https://react-simple-animate.now.sh/
MIT License
1.82k stars 61 forks source link

useAnimateGroup doesn't work as expected after the second time the play function gets called #97

Closed ali-garajian closed 2 years ago

ali-garajian commented 2 years ago

Describe the bug useAnimateGroup's play function only works for the first two times it's called. After that the value of isPlaying doesn't get updated correctly and remains true no matter what is passed to play

To Reproduce You can test this behavior in the demo provided in the docs for this hook : https://react-simple-animate.vercel.app/hooks

Expected behavior Calling the play function should update the isPlaying state correctly

Screenshots image

Additional context the cause of this issue is how the play function is internally defined.

playRef.current = playRef.current
    ? playRef.current
    : (isPlay: boolean) => {
        ...
        setStyles(isPlay ? styles : [...styles].reverse());
        setPlaying(!isPlaying);
      };

As you can see, the function assigned to playRef.current is defined only on the first render and creates a closure on the value of isPlaying, which is initially false. Then, when we call play(!isPlaying), isPlaying gets set to true. But after the first render, because playRef.current keeps its old reference which has closed on the initial value of isPlaying, being false, calling play would always call setPlaying(true).

The solution would be to use the parameter isPlay and replace setPlaying(!isPlaying) with setPlaying(isPlay)

Also there is no test for this use case.

If you agree with the diagnosis, I'd be happy to create a PR

bluebill1049 commented 2 years ago

Send us a PR, that would be lovely.