Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

utils.ts

145 lines3.8 KB

1import * as React from 'react'
2import type { RouteIds } from './routeInfo'
3import type { AnyRouter } from './router'
4import type { ConstrainLiteral } from '@tanstack/router-core'
5​
6export function useStableCallback<T extends (...args: Array<any>) => any>(
7 fn: T,
8): T {
9 const fnRef = React.useRef(fn)
10 fnRef.current = fn
11​
12 const ref = React.useRef((...args: Array<any>) => fnRef.current(...args))
13 return ref.current as T
15​
16export type StrictOrFrom<
17 TRouter extends AnyRouter,
18 TFrom,
19 TStrict extends boolean = true,
20> = TStrict extends false
21 ? {
22 from?: never
23 strict: TStrict
24 }
25 : {
26 from: ConstrainLiteral<TFrom, RouteIds<TRouter['routeTree']>>
27 strict?: TStrict
28 }
29​
30export const useLayoutEffect =
31 typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect
32​
33/**
34 * Taken from https://www.developerway.com/posts/implementing-advanced-use-previous-hook#part3
35 */
36export function usePrevious<T>(value: T): T | null {
37 // initialise the ref with previous and current values
38 const ref = React.useRef<{ value: T; prev: T | null }>({
39 value: value,
40 prev: null,
41 })
42​
43 const current = ref.current.value
44​
45 // if the value passed into hook doesn't match what we store as "current"
46 // move the "current" to the "previous"
47 // and store the passed value as "current"
48 if (value !== current) {
49 ref.current = {
50 value: value,
51 prev: current,
52 }
53 }
54​
55 // return the previous value only
56 return ref.current.prev
58​
59/**
60 * React hook to wrap `IntersectionObserver`.
61 *
62 * This hook will create an `IntersectionObserver` and observe the ref passed to it.
63 *
64 * When the intersection changes, the callback will be called with the `IntersectionObserverEntry`.
65 *
66 * @param ref - The ref to observe
67 * @param intersectionObserverOptions - The options to pass to the IntersectionObserver
68 * @param options - The options to pass to the hook
69 * @param callback - The callback to call when the intersection changes
70 * @returns The IntersectionObserver instance
71 * @example
72 * ```tsx
73 * const MyComponent = () => {
74 * const ref = React.useRef<HTMLDivElement>(null)
75 * useIntersectionObserver(
76 * ref,
77 * (entry) => { doSomething(entry) },
78 * { rootMargin: '10px' },
79 * { disabled: false }
80 * )
81 * return <div ref={ref} />
82 * ```
83 */
84export function useIntersectionObserver<T extends Element>(
85 ref: React.RefObject<T | null>,
86 callback: (entry: IntersectionObserverEntry | undefined) => void,
87 intersectionObserverOptions: IntersectionObserverInit = {},
88 options: { disabled?: boolean } = {},
89): IntersectionObserver | null {
90 const isIntersectionObserverAvailable = React.useRef(
91 typeof IntersectionObserver === 'function',
92 )
93​
94 const observerRef = React.useRef<IntersectionObserver | null>(null)
95​
96 React.useEffect(() => {
97 if (
98 !ref.current ||
99 !isIntersectionObserverAvailable.current ||
100 options.disabled
101 ) {
102 return
103 }
104​
105 observerRef.current = new IntersectionObserver(([entry]) => {
106 callback(entry)
107 }, intersectionObserverOptions)
108​
109 observerRef.current.observe(ref.current)
110​
111 return () => {
112 observerRef.current?.disconnect()
113 }
114 }, [callback, intersectionObserverOptions, options.disabled, ref])
115​
116 return observerRef.current
118​
119/**
120 * React hook to take a `React.ForwardedRef` and returns a `ref` that can be used on a DOM element.
121 *
122 * @param ref - The forwarded ref
123 * @returns The inner ref returned by `useRef`
124 * @example
125 * ```tsx
126 * const MyComponent = React.forwardRef((props, ref) => {
127 * const innerRef = useForwardedRef(ref)
128 * return <div ref={innerRef} />
129 * })
130 * ```
131 */
132export function useForwardedRef<T>(ref?: React.ForwardedRef<T>) {
133 const innerRef = React.useRef<T>(null)
134​
135 React.useEffect(() => {
136 if (!ref) return
137 if (typeof ref === 'function') {
138 ref(innerRef.current)
139 } else {
140 ref.current = innerRef.current
141 }
142 })
143​
144 return innerRef