UNPKG

@tanstack/react-router

Version:

Modern and scalable routing for React applications

86 lines (85 loc) 2.55 kB
import * as React$1 from "react"; /** * React.use if available (React 19+), undefined otherwise. * Use dynamic lookup to avoid Webpack compilation errors with React 18. */ var reactUse = React$1["use"]; var useLayoutEffect = typeof window !== "undefined" ? React$1.useLayoutEffect : React$1.useEffect; /** * Taken from https://www.developerway.com/posts/implementing-advanced-use-previous-hook#part3 */ function usePrevious(value) { const ref = React$1.useRef({ value, prev: null }); const current = ref.current.value; if (value !== current) ref.current = { value, prev: current }; return ref.current.prev; } /** * React hook to wrap `IntersectionObserver`. * * This hook will create an `IntersectionObserver` and observe the ref passed to it. * * When the intersection changes, the callback will be called with the `IntersectionObserverEntry`. * * @param ref - The ref to observe * @param intersectionObserverOptions - The options to pass to the IntersectionObserver * @param options - The options to pass to the hook * @param callback - The callback to call when the intersection changes * @returns The IntersectionObserver instance * @example * ```tsx * const MyComponent = () => { * const ref = React.useRef<HTMLDivElement>(null) * useIntersectionObserver( * ref, * (entry) => { doSomething(entry) }, * { rootMargin: '10px' }, * { disabled: false } * ) * return <div ref={ref} /> * ``` */ function useIntersectionObserver(ref, callback, intersectionObserverOptions = {}, options = {}) { React$1.useEffect(() => { if (!ref.current || options.disabled || typeof IntersectionObserver !== "function") return; const observer = new IntersectionObserver(([entry]) => { callback(entry); }, intersectionObserverOptions); observer.observe(ref.current); return () => { observer.disconnect(); }; }, [ callback, intersectionObserverOptions, options.disabled, ref ]); } /** * React hook to take a `React.ForwardedRef` and returns a `ref` that can be used on a DOM element. * * @param ref - The forwarded ref * @returns The inner ref returned by `useRef` * @example * ```tsx * const MyComponent = React.forwardRef((props, ref) => { * const innerRef = useForwardedRef(ref) * return <div ref={innerRef} /> * }) * ``` */ function useForwardedRef(ref) { const innerRef = React$1.useRef(null); React$1.useImperativeHandle(ref, () => innerRef.current, []); return innerRef; } //#endregion export { reactUse, useForwardedRef, useIntersectionObserver, useLayoutEffect, usePrevious }; //# sourceMappingURL=utils.js.map