( ref?: ((instance: T | null) => (() => void) | void) | MutableRefObject<T | null> | null )
| 22 | * @see https://react.dev/reference/react/forwardRef |
| 23 | */ |
| 24 | export function useObjectRef<T>( |
| 25 | ref?: ((instance: T | null) => (() => void) | void) | MutableRefObject<T | null> | null |
| 26 | ): MutableRefObject<T | null> { |
| 27 | const objRef: MutableRefObject<T | null> = useRef<T>(null); |
| 28 | const cleanupRef: MutableRefObject<(() => void) | void> = useRef(undefined); |
| 29 | |
| 30 | const refEffect = useCallback( |
| 31 | (instance: T | null) => { |
| 32 | if (typeof ref === 'function') { |
| 33 | const refCallback = ref; |
| 34 | const refCleanup = refCallback(instance); |
| 35 | return () => { |
| 36 | if (typeof refCleanup === 'function') { |
| 37 | refCleanup(); |
| 38 | } else { |
| 39 | refCallback(null); |
| 40 | } |
| 41 | }; |
| 42 | } else if (ref) { |
| 43 | ref.current = instance; |
| 44 | return () => { |
| 45 | ref.current = null; |
| 46 | }; |
| 47 | } |
| 48 | }, |
| 49 | [ref] |
| 50 | ); |
| 51 | |
| 52 | return useMemo( |
| 53 | () => ({ |
| 54 | get current() { |
| 55 | return objRef.current; |
| 56 | }, |
| 57 | set current(value) { |
| 58 | objRef.current = value; |
| 59 | if (cleanupRef.current) { |
| 60 | cleanupRef.current(); |
| 61 | cleanupRef.current = undefined; |
| 62 | } |
| 63 | |
| 64 | if (value != null) { |
| 65 | cleanupRef.current = refEffect(value); |
| 66 | } |
| 67 | } |
| 68 | }), |
| 69 | [refEffect] |
| 70 | ); |
| 71 | } |
no outgoing calls
no test coverage detected