env.ts
Overview
The env.ts file provides environment-related constants, utility functions, and React hooks that help manage differences between server-side and client-side execution contexts. It focuses on:
Detecting whether the code is running on a server or client (browser).
Providing a cross-environment safe version of React's
useLayoutEffecthook.Polyfilling the
requestAnimationFrameAPI where not available.Detecting slow network connections for adaptive behavior.
This file is typically used in React projects that support server-side rendering (SSR) or run in diverse JavaScript environments (like Deno), ensuring smooth and warning-free operation across these platforms.
Detailed Explanations
Constants
IS_REACT_LEGACY: boolean
Description: Determines if the React version used is a legacy version that does not support the useId hook.
Implementation: Checks for the existence of React.useId and negates it.
Usage: Can be used to conditionally apply different logic depending on React version compatibility.
IS_SERVER: boolean
Description: Detects if the code is running in a server environment.
Implementation: Uses two helper flags:
!isWindowDefined (true if
windowis undefined, indicating server or non-browser environment)isLegacyDeno(detects legacy Deno runtime)
Usage: Used to conditionally run client-only code or avoid running browser-specific hooks on the server.
Functions
rAF(f: (...args: any[]) => void): number | ReturnType<typeof setTimeout>
Description: A polyfill for
requestAnimationFramethat falls back tosetTimeoutifrequestAnimationFrameis not available.Parameters:
f: A callback function to be invoked before the next repaint or after a timeout.
Returns:
The ID returned by
requestAnimationFrameorsetTimeout, which can be used to cancel the callback.
Usage:
rAF(() => { // animation or UI update logic here });Implementation details:
Uses the helper
hasRequestAnimationFrame()to check availability.Calls
window.requestAnimationFrame(f)if available.Otherwise, calls
setTimeout(f, 1)as a fallback.
Hooks
useIsomorphicLayoutEffect
Description: A React hook that uses
useLayoutEffectin the browser but switches touseEffecton the server to avoid React warnings during SSR.Type:
typeof useEffect | typeof useLayoutEffectImplementation:
If
IS_SERVERis true, it assignsuseEffect(no-op on server).Otherwise, it assigns
useLayoutEffect(runs synchronously after DOM mutations).
Usage:
useIsomorphicLayoutEffect(() => { // DOM manipulation or layout effect logic here }, []);Purpose:
Prevents React warnings about
useLayoutEffectusage on server environments.Provides a seamless hook that works both server- and client-side.
Properties
navigatorConnection
Description: Extends the
navigatorobject to access network connection information safely.Type:
Navigator & { connection?: { effectiveType: string; saveData: boolean } } | falseImplementation:
Checks if
navigatoris defined.Casts it to an extended type that includes the
connectionproperty.Attempts to retrieve the
connectionobject.
Usage: Used internally to detect network speed or data-saving preferences.
slowConnection: boolean
Description: Detects if the current network connection is considered "slow".
Implementation:
Returns
falseon server or if connection info is unavailable.Checks if the connection's
effectiveTypeis'slow-2g'or'2g'.Checks if the user has enabled
saveData.
Usage:
Used to adjust application behavior/configuration for users on slow networks.
Example: reduce image sizes, disable animations, defer non-critical requests.
Example:
if (slowConnection) { // Load low-quality images or disable animations }
Implementation Details & Algorithms
Environment Detection:
Combines multiple runtime checks (
windowpresence, legacy Deno detection) to accurately determine server vs client environment.
Polyfill Strategy:
Uses feature detection for
requestAnimationFrameand falls back tosetTimeoutwith minimal delay.
Isomorphic Hook:
Avoids React SSR warnings by swapping out
useLayoutEffectwithuseEffecton server.
Network Connection API Usage:
Uses browser
navigator.connectionAPI to detect network conditions.The detection logic focuses on limiting app behavior on known slow connections or when data saver mode is active.
Interaction with Other Files
Imports helper functions from
./helper:hasRequestAnimationFrame(): to check ifrequestAnimationFrameexists.isLegacyDeno: to detect legacy Deno runtime.isWindowDefined: to check ifwindowis defined.
Used by React components or hooks that require:
Environment-aware hooks (
useIsomorphicLayoutEffect).Network adaptive logic (
slowConnection).Cross-environment animation frame scheduling (
rAF).
Forms a foundational utility module for environment detection and polyfills, facilitating robust cross-platform React app behavior.
Usage Examples
import React from 'react'
import { useIsomorphicLayoutEffect, slowConnection, rAF } from './env'
function MyComponent() {
useIsomorphicLayoutEffect(() => {
let animationId = rAF(() => {
console.log('Animation frame or fallback timeout triggered')
})
return () => {
if ('cancelAnimationFrame' in window) {
cancelAnimationFrame(animationId as number)
} else {
clearTimeout(animationId as number)
}
}
}, [])
return (
<div>
{slowConnection ? (
<p>You are on a slow connection. Loading optimized content...</p>
) : (
<p>Welcome, enjoy the full experience!</p>
)}
</div>
)
}
Mermaid Diagram: File Structure and Relationships
flowchart TD
A[env.ts]
A --> IS_REACT_LEGACY[IS_REACT_LEGACY:boolean]
A --> IS_SERVER[IS_SERVER:boolean]
A --> rAF[rAF(f: Function): number | TimeoutId]
A --> useIsomorphicLayoutEffect[useIsomorphicLayoutEffect: Hook]
A --> navigatorConnection[navigatorConnection: Navigator | false]
A --> slowConnection[slowConnection:boolean]
subgraph Helpers
H1[hasRequestAnimationFrame()]
H2[isLegacyDeno]
H3[isWindowDefined]
end
A -->|imports| Helpers
rAF -->|uses| H1
IS_SERVER -->|uses| H2 & H3
useIsomorphicLayoutEffect -->|uses| IS_SERVER
slowConnection -->|uses| navigatorConnection & IS_SERVER
Summary
The env.ts file is a utility module that abstracts environment detection and polyfills for React applications running in mixed environments (client, server, legacy runtimes). It exports constants for environment flags, a cross-platform requestAnimationFrame polyfill, an isomorphic React hook for layout effects, and connection speed detection logic. It is essential for building resilient React components that function correctly across SSR and client browsers, adapting to network conditions and runtime capabilities seamlessly.