Created
May 15, 2020 02:47
-
-
Save balmacefa/3e899642ae96eeb78e76d015d9587397 to your computer and use it in GitHub Desktop.
React Frame Loop Hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import {useRef, useEffect} from 'react' | |
| export const useFrameLoop = (callback) => { | |
| const requestID = useRef(); | |
| const previousTime = useRef(); | |
| const loop = time => { | |
| if (previousTime.current !== undefined) { | |
| const deltaTime = time - previousTime.current; | |
| callback(time, deltaTime); | |
| } | |
| previousTime.current = time; | |
| requestID.current = requestAnimationFrame(loop); | |
| } | |
| useEffect(()=>{ | |
| requestID.current = requestAnimationFrame(loop); | |
| return ()=> cancelAnimationFrame(requestID.current); | |
| }, []); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment