useForkRef
Sends one ref value to two mutable or callback refs.
About
useForkRef combines two refs so a single element can satisfy an internal ref and a consumer-provided ref. Both mutable refs and callback refs are supported.
Example
import { useCallback, useRef, useState } from "react";
import { useForkRef } from "rooks";
export default function SharedInputRef() {
const inputRef = useRef<HTMLInputElement | null>(null);
const [connected, setConnected] = useState(false);
const reportRef = useCallback((node: HTMLInputElement | null) => {
setConnected(node !== null);
}, []);
const sharedRef = useForkRef(inputRef, reportRef);
return (
<label>
Name <input ref={sharedRef} />
<span>{connected ? " connected" : " disconnected"}</span>
</label>
);
}Parameters
refA,refB— a React mutable ref, callback ref,null, orundefined, both receiving the same value.
Return value
Returns a memoized callback ref, or null when both inputs are null. React supplies the element on attachment and null on detachment.
Behavior and lifecycle
The combined ref is stable while both input refs are stable. If either input changes, React calls the old combined ref with null before attaching through the new one, naturally cleaning up both destinations. Callback refs are invoked in argument order; an exception from the first prevents the second from being updated.
Compatibility and accessibility
The hook is SSR-safe and performs work only when React attaches a ref. It does not change the element's semantics, focus behavior, or accessible name.
Related
- useMergeRefs combines any number of refs.