'React onClick function side affects messing with animation
My function is messing up my animation. I have a little audio player that uses onClick play/pause button to help manage information for a couple useStates (currentTime and duration) to and move the progress bar and update the time ticker while the song is playing and stop when the song is paused. So it runs every second. I also want an animation to start and pause onClick of the same button. Problem is, every time it runs, it resets the animation so it . Any help would be greatly appreciated. Thanks, ya'll.
const [isPlaying, setIsPlaying] = useState(false);
const [duration, setDuration] = useState(0);
const [currentTime, setCurrentTime] = useState(0);
const [animation, setAnimation] = useState(false);
const isPlayingHandler = () => {
const prevValue = isPlaying;
setIsPlaying(!prevValue);
if (!prevValue) {
audio.current.play();
setAnimation(true);
progressBarAnimation.current = requestAnimationFrame(whilePlaying);
} else {
audio.current.pause();
setAnimation(false);
cancelAnimationFrame(progressBarAnimation.current);
};
<button className={styles.playPauseButton} onClick={isPlayingHandler}>
{ isPlaying ? <BsPauseCircleFill /> : <BsPlayCircleFill /> }</button>
There is way more code but these are the bits that affect the animation state.
Solution 1:[1]
It's working fine by default the component's animation will be re-rendered. The solution when you want to not to let specific part of the application to re-render ( always ) is to wrap that thing into useCallback function ( it will return the memoized animations which will change iff dependency array of it changes ( same as useEffect )). Here is how your code will look like ( it's just and idea ):
const memoizedCallback = useCallback(
() => {
const prevValue = isPlaying;
setIsPlaying(!prevValue);
if (!prevValue) {
audio.current.play();
setAnimation(true);
progressBarAnimation.current =
requestAnimationFrame(whilePlaying);
} else {
audio.current.pause();
setAnimation(false);
cancelAnimationFrame(progressBarAnimation.current);
},
[setAnimation, requestAnimationFrame, animation],
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Asad Ashraf |
