mirror of
https://github.com/Nezumi-2711/react-training.git
synced 2026-09-22 20:01:59 +00:00
26 lines
484 B
TypeScript
26 lines
484 B
TypeScript
import { ForwardedRef, useEffect, useRef } from 'react';
|
|
|
|
// Types
|
|
import { Nullable } from '../globals/types';
|
|
|
|
const useForwardRef = <T>(
|
|
ref: ForwardedRef<T>,
|
|
initialValue: Nullable<T> = null
|
|
) => {
|
|
const targetRef = useRef<T>(initialValue);
|
|
|
|
useEffect(() => {
|
|
if (!ref) return;
|
|
|
|
if (typeof ref === 'function') {
|
|
ref(targetRef.current);
|
|
} else {
|
|
ref.current = targetRef.current;
|
|
}
|
|
}, [ref]);
|
|
|
|
return targetRef;
|
|
};
|
|
|
|
export { useForwardRef };
|