File tree Expand file tree Collapse file tree 1 file changed +23
-0
lines changed Expand file tree Collapse file tree 1 file changed +23
-0
lines changed Original file line number Diff line number Diff line change 3
3
import type { MutableRefObject , Ref , RefCallback } from 'react' ;
4
4
import { useCallback , useRef } from 'react' ;
5
5
6
+ /**
7
+ * A hook that synchronizes an external ref (callback or object) with an internal ref.
8
+ *
9
+ * @example
10
+ * ```tsx
11
+ * const MyComponent = forwardRef<HTMLDivElement, PropTypes>((props, ref) => {
12
+ * const [componentRef, localRef] = useSyncRef<HTMLDivElement>(ref);
13
+ *
14
+ * useEffect(() => {
15
+ * // `localRef.current` is always the latest DOM node (or `null`)
16
+ * console.log('current node:', localRef.current);
17
+ * }, []);
18
+ *
19
+ * return <div ref={componentRef}>Hello World!</div>;
20
+ * });
21
+ * ```
22
+ *
23
+ * @returns [componentRef, localRef]
24
+ * A tuple containing:
25
+ * - `componentRef`: a stable callback ref to attach to React elements. When the node
26
+ * updates, it will forward the node to the external `ref` and update the internal one.
27
+ * - `localRef`: an internal, ref object that holds the latest node for synchronous reads.
28
+ */
6
29
export function useSyncRef < RefType = never > (
7
30
ref : Ref < RefType > ,
8
31
) : [ RefCallback < RefType > , MutableRefObject < RefType | null > ] {
You can’t perform that action at this time.
0 commit comments