Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 6, 2020 11:50 pm GMT

Need assistance with useEffect() dependencies

Hey there! So I'm trying to figure out how to use canvas element in React.

raf-screenshot

Here is how my playground looks like. Canvas element, a dot travelling around the board and a button to start / stop the animation

The Issue

The button is giving me hard time pausing and resuming the animation. When the dot stops programmatically, it takes a couple of extra clicks on the Start button to keep it moving.

I suspect it has to do with useEffect and its dependencies.

Do you think you could take a look and give me some advice?

The Code

I use requestAnimationFrame() method to update the animation.

const reqRef = useRef()const previousTimeRef = useRef()const animate = time => {    // some animation    if (previousTimeRef.current !== undefined) {        const deltaTime = time - previousTimeRef.current    }    previousTimeRef.current = time    reqRef.current = requestAnimationFrame(animate)    // stop    if (shouldStop) cancelAnimationFrame(reqRef.current)}useEffect(() => {    // start the loop    reqRef.current = requestAnimationFrame(animate)    // clean up    return () => cancelAnimationFrame(reqRef.current) }, [shouldStop, previousTimeRef.current])
Enter fullscreen mode Exit fullscreen mode
  • animate() function loops itself
  • useEffect() starts the animation
  • requestAnimationFrame() method generates new reqRef value with each run
  • in order to stop the animation you have to use cancelAnimationFrame(reqRef.current) with the current reqRef

Approach

I use shouldStop as a key to pause the animation.

 const [shouldStop, setShouldStop] = useState(true)<button onClick={() => setShouldStop(!shouldStop)}>
Enter fullscreen mode Exit fullscreen mode

At the start it works as expected

  • The button flips the key
  • useEffect fires, as shouldStop is set as its dependency, and sets the loop
    if (positionX < 0) {        setPositionX(290)        setPositionY(165)        setShouldStop(!shouldStop)    }
Enter fullscreen mode Exit fullscreen mode

When the dot bounces at the edge, the app resets its position and flips the key back to true. The dot rests in the middle of the screen.

And now when I press the button, the key switches to false yet nothing happens. After the second click key switches to true again. And only on the third time the key switches to false and the dot starts moving.

So

I guess I have three questions

  • Is it a proper approach overall?
  • What am I missing about the useEffect()?
  • How do you trace / investigate those issues?

Original Link: https://dev.to/ptifur/need-assistance-with-requestanimationframe-in-react-5gdc

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To