0

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 Playgroundcomponent 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>
})
James
  • 1,355
  • 3
  • 14
  • 38
  • your usage of `useCallback` seems wrong, it seems you need `useEffect` instead. `useCallback` memoizes function passed to it and only recreates new function is any of the dependency passed to it in `[]` changes – Rikin Oct 25 '19 at 13:54
  • Thanks for your comment. I know it seems wrong but it works... – James Oct 25 '19 at 14:22

0 Answers0