Following along from a Scrimba tutorial on React Hooks, I've been trying to use, useEffect
and useCallback
for ways of preventing a component from re-rendering during requestAnimationFrame. I currently have the Playground
component that updates and renders count
state and a child <Calculate />
component that counts the number of renders.
Below, I'm using useCallback and It seems to be working. Does anyone know if the return function works in a useCallback hook to clean up the requestAnimationframe as it would in the useEffect hook? I've used it in the below code, but not sure how to check if 'cancelAnimationFrame' is being implemented?
import React, { useState, useRef, useCallback } from 'react'
export default function Playground() {
const [count, setCount] = useState(0)
const cb = useCallback(()=>{
let anim,
loop = () => {
setCount(prev => prev + 1)
anim = requestAnimationFrame(loop)
}
loop()
return()=> cancelAnimationFrame(anim)
}, [])
return (
<>
<h1>{count}</h1>
<Calculate cb={cb} />
</>
)
}
const Calculate = React.memo(({ cb }) =>{
cb()
const renderCount = useRef(1)
return <div>{renderCount.current++}</div>
})