@@ -8,10 +8,11 @@ import React, {
8
8
forwardRef ,
9
9
useImperativeHandle ,
10
10
RefObject ,
11
+ useMemo ,
11
12
} from 'react'
12
13
import { useThree , useFrame , createPortal } from '@react-three/fiber'
13
14
import { CopyPass , DepthPickingPass , DepthOfFieldEffect } from 'postprocessing'
14
- import { DepthOfField , EffectComposerContext } from './index '
15
+ import { DepthOfField , EffectComposerContext } from '.. '
15
16
import { easing } from 'maath'
16
17
17
18
export type AutofocusProps = typeof DepthOfField & {
@@ -42,8 +43,8 @@ export const Autofocus = forwardRef<AutofocusApi, AutofocusProps>(
42
43
const { composer, camera } = useContext ( EffectComposerContext )
43
44
44
45
// see: https://codesandbox.io/s/depthpickingpass-x130hg
45
- const [ depthPickingPass ] = useState ( new DepthPickingPass ( ) )
46
- const [ copyPass ] = useState ( new CopyPass ( ) )
46
+ const [ depthPickingPass ] = useState ( ( ) => new DepthPickingPass ( ) )
47
+ const [ copyPass ] = useState ( ( ) => new CopyPass ( ) )
47
48
useEffect ( ( ) => {
48
49
composer . addPass ( depthPickingPass )
49
50
composer . addPass ( copyPass )
@@ -53,9 +54,16 @@ export const Autofocus = forwardRef<AutofocusApi, AutofocusProps>(
53
54
}
54
55
} , [ composer , depthPickingPass , copyPass ] )
55
56
56
- const [ hitpoint ] = useState ( new THREE . Vector3 ( 0 , 0 , 0 ) )
57
+ useEffect ( ( ) => {
58
+ return ( ) => {
59
+ depthPickingPass . dispose ( )
60
+ copyPass . dispose ( )
61
+ }
62
+ } , [ depthPickingPass , copyPass ] )
63
+
64
+ const [ hitpoint ] = useState ( ( ) => new THREE . Vector3 ( 0 , 0 , 0 ) )
57
65
58
- const [ ndc ] = useState ( new THREE . Vector3 ( 0 , 0 , 0 ) )
66
+ const [ ndc ] = useState ( ( ) => new THREE . Vector3 ( 0 , 0 , 0 ) )
59
67
const getHit = useCallback (
60
68
async ( x : number , y : number ) => {
61
69
ndc . x = x
@@ -104,15 +112,15 @@ export const Autofocus = forwardRef<AutofocusApi, AutofocusProps>(
104
112
} )
105
113
106
114
// Ref API
107
- useImperativeHandle (
108
- fref ,
115
+ const api = useMemo < AutofocusApi > (
109
116
( ) => ( {
110
117
dofRef,
111
118
hitpoint,
112
119
update,
113
120
} ) ,
114
121
[ hitpoint , update ]
115
122
)
123
+ useImperativeHandle ( fref , ( ) => api , [ api ] )
116
124
117
125
return (
118
126
< >
0 commit comments