diff --git a/.changeset/neat-pumas-thank.md b/.changeset/neat-pumas-thank.md new file mode 100644 index 0000000000..4235f43c1b --- /dev/null +++ b/.changeset/neat-pumas-thank.md @@ -0,0 +1,5 @@ +--- +"@lynx-js/react": patch +--- + +refactor: make `useEffect`, `useLayoutEffect` and `useImperativeHandle` no-op on the main thread diff --git a/packages/react/runtime/src/hooks/react.ts b/packages/react/runtime/src/hooks/react.ts index 91fb6dfc4a..6f519e1127 100644 --- a/packages/react/runtime/src/hooks/react.ts +++ b/packages/react/runtime/src/hooks/react.ts @@ -7,10 +7,10 @@ import { useDebugValue, useErrorBoundary, useId, - useImperativeHandle, useMemo, useEffect as usePreactEffect, useState as usePreactState, + useImperativeHandle as usePreactUseImperativeHandle, useReducer, useRef, } from 'preact/hooks'; @@ -20,6 +20,7 @@ import type { DependencyList, EffectCallback } from 'react'; import type { TraceOption } from '@lynx-js/types'; import { isProfiling, profileEnd, profileFlowId, profileStart } from '../debug/profile.js'; +import { noop } from '../utils.js'; type GenericSetState = Dispatch>; @@ -135,9 +136,11 @@ const useState: typeof usePreactState = isProfiling * * @public */ -const useEffect: (effect: EffectCallback, deps?: DependencyList) => void = isProfiling - ? useEffectProfiled - : usePreactEffect; +const useEffect: (effect: EffectCallback, deps?: DependencyList) => void = __BACKGROUND__ + ? (isProfiling + ? useEffectProfiled + : usePreactEffect) + : noop; /** * `useLayoutEffect` is now an alias of `useEffect`. Use `useEffect` instead. @@ -151,9 +154,13 @@ const useEffect: (effect: EffectCallback, deps?: DependencyList) => void = isPro * * @deprecated `useLayoutEffect` in the background thread cannot offer the precise timing for reading layout information and synchronously re-render, which is different from React. */ -const useLayoutEffect: (effect: EffectCallback, deps?: DependencyList) => void = isProfiling - ? useLayoutEffectProfiled - : usePreactEffect; +const useLayoutEffect: (effect: EffectCallback, deps?: DependencyList) => void = __BACKGROUND__ + ? (isProfiling + ? useLayoutEffectProfiled + : usePreactEffect) + : noop; + +const useImperativeHandle: typeof usePreactUseImperativeHandle = __BACKGROUND__ ? usePreactUseImperativeHandle : noop; export { // preact diff --git a/packages/react/runtime/src/utils.ts b/packages/react/runtime/src/utils.ts index 518f0f577c..da29803abd 100644 --- a/packages/react/runtime/src/utils.ts +++ b/packages/react/runtime/src/utils.ts @@ -6,6 +6,10 @@ import type { ComponentClass } from 'preact'; import { getCurrentVNode, getOwnerStack } from './debug/component-stack.js'; +/* v8 ignore start */ +export const noop: (...args: unknown[]) => unknown = () => {}; +/* v8 ignore end */ + export function isDirectOrDeepEqual(a: any, b: any): boolean { if (a === b) { return true;