react-laze
Version:
Lazily render components in React
110 lines (101 loc) • 3.01 kB
JavaScript
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
default: () => useLaze
});
module.exports = __toCommonJS(src_exports);
// src/useLaze.ts
var import_react4 = require("react");
// src/useReactiveRef.ts
var import_react3 = require("react");
// src/useConstant.ts
var import_react2 = require("react");
// src/useLazyRef.ts
var import_react = require("react");
function useLazyRef(supplier) {
const ref = (0, import_react.useRef)();
if (!ref.current) {
ref.current = {
current: supplier()
};
}
(0, import_react.useDebugValue)(ref.current);
return ref.current;
}
// src/useConstant.ts
function useConstant(supplier) {
const { current } = useLazyRef(supplier);
(0, import_react2.useDebugValue)(current);
return current;
}
// src/useReactiveRef.ts
function useReactiveRef(supplier) {
const [state, setState] = (0, import_react3.useState)(supplier);
const ref = useLazyRef(supplier);
if (ref.current !== state) {
ref.current = state;
}
const proxyObject = useConstant(() => ({
get current() {
return ref.current;
},
set current(value) {
setState(() => value);
}
}));
(0, import_react3.useDebugValue)(proxyObject);
return proxyObject;
}
// src/useLaze.ts
function useLaze(options) {
const [visible, setVisible] = (0, import_react4.useState)(false);
const ref = useReactiveRef(() => null);
const { current } = ref;
const shouldRefresh = options == null ? void 0 : options.refresh;
(0, import_react4.useEffect)(() => {
setVisible(false);
if (current) {
const observer = new IntersectionObserver((entries) => {
for (const entry of entries) {
if (shouldRefresh) {
setVisible(entry.isIntersecting);
} else if (entry.isIntersecting) {
setVisible(true);
observer.disconnect();
}
}
});
observer.observe(current);
return () => {
observer.unobserve(current);
observer.disconnect();
};
}
return void 0;
}, [current, shouldRefresh]);
const value = {
ref,
visible
};
(0, import_react4.useDebugValue)(value);
return value;
}
//# sourceMappingURL=index.cjs.map
;