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

utils.ts

59 lines1.8 KB

1'use client'
2import * as React from 'react'
3import { isServer } from '@tanstack/router-core/isServer'
4​
5// Safe version of React.use() that will not cause compilation errors against
6// React 18 with Webpack, which statically analyzes imports and fails when it
7// sees React.use referenced (since 'use' is not exported from React 18).
8// This uses a dynamic string lookup to avoid the static analysis.
9// eslint-disable-next-line prefer-const -- Must be `let` to prevent bundler constant-folding
10let REACT_USE = 'use'
11​
12/**
13 * React.use if available (React 19+), undefined otherwise.
14 * Use dynamic lookup to avoid Webpack compilation errors with React 18.
15 */
16export const reactUse:
17 | (<T>(usable: Promise<T> | React.Context<T>) => T)
18 | undefined = (React as any)[REACT_USE]
19​
20export function useStableCallback<T extends (...args: Array<any>) => any>(
21 fn: T,
22): T {
23 const fnRef = React.useRef(fn)
24 fnRef.current = fn
25​
26 const ref = React.useRef((...args: Array<any>) => fnRef.current(...args))
27 return ref.current as T
29​
30export const useLayoutEffect =
31 (isServer ?? typeof window === 'undefined')
32 ? React.useEffect
33 : React.useLayoutEffect
34​
35/**
36 * Taken from https://www.developerway.com/posts/implementing-advanced-use-previous-hook#part3
37 */
38export function usePrevious<T>(value: T): T | null {
39 // initialise the ref with previous and current values
40 const ref = React.useRef<{ value: T; prev: T | null }>({
41 value: value,
42 prev: null,
43 })
44​
45 const current = ref.current.value
46​
47 // if the value passed into hook doesn't match what we store as "current"
48 // move the "current" to the "previous"
49 // and store the passed value as "current"
50 if (value !== current) {
51 ref.current = {
52 value: value,
53 prev: current,
54 }
55 }
56​
57 // return the previous value only
58 return ref.current.prev