next
Version:
The React Framework
69 lines (67 loc) • 2.4 kB
JavaScript
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "useMergedRef", {
enumerable: true,
get: function() {
return useMergedRef;
}
});
const _react = require("react");
function useMergedRef(refA, refB) {
const cleanupA = (0, _react.useRef)(null);
const cleanupB = (0, _react.useRef)(null);
// NOTE: In theory, we could skip the wrapping if only one of the refs is non-null.
// (this happens often if the user doesn't pass a ref to Link/Form/Image)
// But this can cause us to leak a cleanup-ref into user code (e.g. via `<Link legacyBehavior>`),
// and the user might pass that ref into ref-merging library that doesn't support cleanup refs
// (because it hasn't been updated for React 19)
// which can then cause things to blow up, because a cleanup-returning ref gets called with `null`.
// So in practice, it's safer to be defensive and always wrap the ref, even on React 19.
return (0, _react.useCallback)((current)=>{
if (current === null) {
const cleanupFnA = cleanupA.current;
if (cleanupFnA) {
cleanupA.current = null;
cleanupFnA();
}
const cleanupFnB = cleanupB.current;
if (cleanupFnB) {
cleanupB.current = null;
cleanupFnB();
}
} else {
if (refA) {
cleanupA.current = applyRef(refA, current);
}
if (refB) {
cleanupB.current = applyRef(refB, current);
}
}
}, [
refA,
refB
]);
}
function applyRef(refA, current) {
if (typeof refA === 'function') {
const cleanup = refA(current);
if (typeof cleanup === 'function') {
return cleanup;
} else {
return ()=>refA(null);
}
} else {
refA.current = current;
return ()=>{
refA.current = null;
};
}
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=use-merged-ref.js.map
;