forked from molefrog/wouter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreact-deps.js
66 lines (59 loc) · 2.35 KB
/
react-deps.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import * as React from "react";
// React.useInsertionEffect is not available in React <18
const {
useEffect,
useLayoutEffect,
useRef,
useInsertionEffect: useBuiltinInsertionEffect,
} = React;
export {
useState,
useContext,
createContext,
isValidElement,
cloneElement,
createElement,
Fragment,
forwardRef,
} from "react";
// To resolve webpack 5 errors, while not presenting problems for native,
// we copy the approaches from https://github.com/TanStack/query/pull/3561
// and https://github.com/TanStack/query/pull/3601
// ~ Show this aging PR some love to remove the need for this hack:
// https://github.com/facebook/react/pull/25231 ~
export { useSyncExternalStore } from "./use-sync-external-store.js";
// Copied from:
// https://github.com/facebook/react/blob/main/packages/shared/ExecutionEnvironment.js
const canUseDOM = !!(
typeof window !== "undefined" &&
typeof window.document !== "undefined" &&
typeof window.document.createElement !== "undefined"
);
// Copied from:
// https://github.com/reduxjs/react-redux/blob/master/src/utils/useIsomorphicLayoutEffect.ts
// "React currently throws a warning when using useLayoutEffect on the server.
// To get around it, we can conditionally useEffect on the server (no-op) and
// useLayoutEffect in the browser."
export const useIsomorphicLayoutEffect = canUseDOM
? useLayoutEffect
: useEffect;
// useInsertionEffect is already a noop on the server.
// See: https://github.com/facebook/react/blob/main/packages/react-server/src/ReactFizzHooks.js
export const useInsertionEffect =
useBuiltinInsertionEffect || useIsomorphicLayoutEffect;
// Userland polyfill while we wait for the forthcoming
// https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md
// Note: "A high-fidelity polyfill for useEvent is not possible because
// there is no lifecycle or Hook in React that we can use to switch
// .current at the right timing."
// So we will have to make do with this "close enough" approach for now.
export const useEvent = (fn) => {
const ref = useRef([fn, (...args) => ref[0](...args)]).current;
// Per Dan Abramov: useInsertionEffect executes marginally closer to the
// correct timing for ref synchronization than useLayoutEffect on React 18.
// See: https://github.com/facebook/react/pull/25881#issuecomment-1356244360
useInsertionEffect(() => {
ref[0] = fn;
});
return ref[1];
};