| 1 | import { React } from '../utils/react'
|
|---|
| 2 |
|
|---|
| 3 | // React currently throws a warning when using useLayoutEffect on the server.
|
|---|
| 4 | // To get around it, we can conditionally useEffect on the server (no-op) and
|
|---|
| 5 | // useLayoutEffect in the browser. We need useLayoutEffect to ensure the store
|
|---|
| 6 | // subscription callback always has the selector from the latest render commit
|
|---|
| 7 | // available, otherwise a store update may happen between render and the effect,
|
|---|
| 8 | // which may cause missed updates; we also must ensure the store subscription
|
|---|
| 9 | // is created synchronously, otherwise a store update may occur before the
|
|---|
| 10 | // subscription is created and an inconsistent state may be observed
|
|---|
| 11 |
|
|---|
| 12 | // Matches logic in React's `shared/ExecutionEnvironment` file
|
|---|
| 13 | const canUseDOM = () =>
|
|---|
| 14 | !!(
|
|---|
| 15 | typeof window !== 'undefined' &&
|
|---|
| 16 | typeof window.document !== 'undefined' &&
|
|---|
| 17 | typeof window.document.createElement !== 'undefined'
|
|---|
| 18 | )
|
|---|
| 19 |
|
|---|
| 20 | const isDOM = /* @__PURE__ */ canUseDOM()
|
|---|
| 21 |
|
|---|
| 22 | // Under React Native, we know that we always want to use useLayoutEffect
|
|---|
| 23 |
|
|---|
| 24 | /**
|
|---|
| 25 | * Checks if the code is running in a React Native environment.
|
|---|
| 26 | *
|
|---|
| 27 | * @returns Whether the code is running in a React Native environment.
|
|---|
| 28 | *
|
|---|
| 29 | * @see {@link https://github.com/facebook/react-native/issues/1331 Reference}
|
|---|
| 30 | */
|
|---|
| 31 | const isRunningInReactNative = () =>
|
|---|
| 32 | typeof navigator !== 'undefined' && navigator.product === 'ReactNative'
|
|---|
| 33 |
|
|---|
| 34 | const isReactNative = /* @__PURE__ */ isRunningInReactNative()
|
|---|
| 35 |
|
|---|
| 36 | const getUseIsomorphicLayoutEffect = () =>
|
|---|
| 37 | isDOM || isReactNative ? React.useLayoutEffect : React.useEffect
|
|---|
| 38 |
|
|---|
| 39 | export const useIsomorphicLayoutEffect =
|
|---|
| 40 | /* @__PURE__ */ getUseIsomorphicLayoutEffect()
|
|---|