-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* Added useTriggerFrame hook * Used useSyncedRef * changed to useEvent for useTriggerFrame * changed to useEvent for useTriggerFrame --------- Co-authored-by: Michael Pühringer <[email protected]>
- Loading branch information
1 parent
f15259c
commit c4c2ba8
Showing
2 changed files
with
52 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
/* eslint-disable react-compiler/react-compiler */ | ||
import * as React from 'react'; | ||
|
||
import isEqual from 'lodash/isEqual'; | ||
import { useEvent } from '../../../hooks'; | ||
|
||
/** | ||
* Hook similar to useEffect that triggers a frame when dependencies change. | ||
* It will deeply compare the dependencies and only trigger a frame if they have changed. | ||
* Frames are debounced to the next animation frame to ensure consistency with the | ||
* display refresh rate. The optional profileId gives insights on the frame timings. | ||
* | ||
* Usage: | ||
* | ||
* ```tsx | ||
* useTriggerFrame(() => { | ||
* // Your frame code here | ||
* }, [dependencies]); | ||
* ``` | ||
*/ | ||
export function useTriggerFrame(frame: () => void, deps: React.DependencyList, profileId?: string) { | ||
const frameRef = React.useRef<number | undefined>(undefined); | ||
const depsRef = React.useRef(deps); | ||
|
||
const callbackEvent = useEvent(frame); | ||
|
||
if (!isEqual(depsRef.current, deps)) { | ||
depsRef.current = deps; | ||
|
||
// Request new frame | ||
if (frameRef.current === undefined) { | ||
frameRef.current = requestAnimationFrame(() => { | ||
frameRef.current = undefined; | ||
|
||
if (profileId) { | ||
let msg = ''; | ||
const t0 = performance.now(); | ||
msg += `Profile: ${profileId}`; | ||
|
||
callbackEvent(); | ||
|
||
const t1 = performance.now(); | ||
msg += ` took ${t1 - t0} milliseconds.`; | ||
console.log(msg); | ||
} else { | ||
callbackEvent(); | ||
} | ||
}); | ||
} | ||
} | ||
} |