@@ -8,10 +8,11 @@ import React, {
88 forwardRef ,
99 useImperativeHandle ,
1010 RefObject ,
11+ useMemo ,
1112} from 'react'
1213import { useThree , useFrame , createPortal } from '@react-three/fiber'
1314import { CopyPass , DepthPickingPass , DepthOfFieldEffect } from 'postprocessing'
14- import { DepthOfField , EffectComposerContext } from './index '
15+ import { DepthOfField , EffectComposerContext } from '.. '
1516import { easing } from 'maath'
1617
1718export type AutofocusProps = typeof DepthOfField & {
@@ -42,8 +43,8 @@ export const Autofocus = forwardRef<AutofocusApi, AutofocusProps>(
4243 const { composer, camera } = useContext ( EffectComposerContext )
4344
4445 // 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 ( ) )
4748 useEffect ( ( ) => {
4849 composer . addPass ( depthPickingPass )
4950 composer . addPass ( copyPass )
@@ -53,9 +54,16 @@ export const Autofocus = forwardRef<AutofocusApi, AutofocusProps>(
5354 }
5455 } , [ composer , depthPickingPass , copyPass ] )
5556
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 ) )
5765
58- const [ ndc ] = useState ( new THREE . Vector3 ( 0 , 0 , 0 ) )
66+ const [ ndc ] = useState ( ( ) => new THREE . Vector3 ( 0 , 0 , 0 ) )
5967 const getHit = useCallback (
6068 async ( x : number , y : number ) => {
6169 ndc . x = x
@@ -104,15 +112,15 @@ export const Autofocus = forwardRef<AutofocusApi, AutofocusProps>(
104112 } )
105113
106114 // Ref API
107- useImperativeHandle (
108- fref ,
115+ const api = useMemo < AutofocusApi > (
109116 ( ) => ( {
110117 dofRef,
111118 hitpoint,
112119 update,
113120 } ) ,
114121 [ hitpoint , update ]
115122 )
123+ useImperativeHandle ( fref , ( ) => api , [ api ] )
116124
117125 return (
118126 < >
0 commit comments