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

utils.ts

88 lines2.4 KB

1import { useEffect, useLayoutEffect, useRef, useState } from 'preact/hooks'
2​
3/**
4 * This is taken from https://github.com/preactjs/preact/blob/main/compat/src/hooks.js#L8-L54
5 * which is taken from https://github.com/facebook/react/blob/main/packages/use-sync-external-store/src/useSyncExternalStoreShimClient.js#L84
6 * on a high level this cuts out the warnings, ... and attempts a smaller implementation.
7 * This way we don't have to import preact/compat with side effects
8 */
9type InternalStore = {
10 _value: any
11 _getSnapshot: () => any
13type StoreRef = {
14 _instance: InternalStore
16export function useSyncExternalStore(
17 subscribe: (onStoreChange: () => void) => () => void,
18 getSnapshot: () => any,
19) {
20 const value = getSnapshot()
21​
22 const [{ _instance }, forceUpdate] = useState<StoreRef>({
23 _instance: { _value: value, _getSnapshot: getSnapshot },
24 })
25​
26 useLayoutEffect(() => {
27 _instance._value = value
28 _instance._getSnapshot = getSnapshot
29​
30 if (didSnapshotChange(_instance)) {
31 forceUpdate({ _instance })
32 }
33 }, [subscribe, value, getSnapshot])
34​
35 useEffect(() => {
36 if (didSnapshotChange(_instance)) {
37 forceUpdate({ _instance })
38 }
39​
40 return subscribe(() => {
41 if (didSnapshotChange(_instance)) {
42 forceUpdate({ _instance })
43 }
44 })
45 }, [subscribe])
46​
47 return value
49​
50function didSnapshotChange(inst: {
51 _getSnapshot: () => any
52 _value: any
53}): boolean {
54 const latestGetSnapshot = inst._getSnapshot
55 const prevValue = inst._value
56 try {
57 const nextValue = latestGetSnapshot()
58 return !Object.is(prevValue, nextValue)
59 // eslint-disable-next-line no-unused-vars
60 } catch (_error) {
61 return true
62 }
64​
65export function useSyncExternalStoreWithSelector<TSnapshot, TSelected>(
66 subscribe: (onStoreChange: () => void) => () => void,
67 getSnapshot: () => TSnapshot,
68 selector: (snapshot: TSnapshot) => TSelected,
69 isEqual: (a: TSelected, b: TSelected) => boolean,
70): TSelected {
71 const selectedSnapshotRef = useRef<TSelected | undefined>()
72​
73 const getSelectedSnapshot = () => {
74 const snapshot = getSnapshot()
75 const selected = selector(snapshot)
76​
77 if (
78 selectedSnapshotRef.current === undefined ||
79 !isEqual(selectedSnapshotRef.current, selected)
80 ) {
81 selectedSnapshotRef.current = selected
82 }
83​
84 return selectedSnapshotRef.current
85 }
86​
87 return useSyncExternalStore(subscribe, getSelectedSnapshot)