-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: use useMutableCallback in useMainLoop
- Loading branch information
Showing
3 changed files
with
38 additions
and
6 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 |
---|---|---|
@@ -1,10 +1,17 @@ | ||
import { useEffect } from 'react' | ||
import { useEffect, useRef } from 'react' | ||
|
||
import { addMainLoopEffect } from '@manapotion/core' | ||
|
||
import type { MainLoopEffectCallback, MainLoopEffectOptions } from '@manapotion/core' | ||
|
||
import { useMutableCallback } from './util' | ||
|
||
export const useMainLoop = (callback: MainLoopEffectCallback, options?: MainLoopEffectOptions) => { | ||
// eslint-disable-next-line react-hooks/exhaustive-deps | ||
useEffect(() => addMainLoopEffect(callback, options), []) | ||
const mutableCallbackRef = useMutableCallback(callback) | ||
const stableOptions = useRef(options) | ||
useEffect( | ||
() => addMainLoopEffect(args => mutableCallbackRef.current(args), stableOptions.current), | ||
// eslint-disable-next-line react-hooks/exhaustive-deps | ||
[], | ||
) | ||
} |
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,15 @@ | ||
import { useEffect, useLayoutEffect, useRef } from 'react' | ||
|
||
// Borrowed from https://github.com/pmndrs/react-three-fiber/blob/master/packages/fiber/src/core/utils.ts | ||
|
||
export const useIsomorphicLayoutEffect = | ||
typeof window !== 'undefined' && | ||
(window.document?.createElement || window.navigator?.product === 'ReactNative') | ||
? useLayoutEffect | ||
: useEffect | ||
|
||
export function useMutableCallback<T>(fn: T) { | ||
const ref = useRef<T>(fn) | ||
useIsomorphicLayoutEffect(() => void (ref.current = fn), [fn]) | ||
return ref | ||
} |