30秒学会 React 片段 · 2023年5月6日

30秒学会 React 片段 – React useIsomporphicEffect hook

Resolves to useEffect() on the server and useLayoutEffect() on the client.

  • Use typeof to check if the Window object is defined. If it is, return the useLayoutEffect(). Otherwise return useEffect().

代码实现

const useIsomorphicEffect =
  typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;

使用样例

const MyApp = () => {
  useIsomorphicEffect(() => {
    window.console.log('Hello');
  }, []);

  return null;
};

ReactDOM.createRoot(document.getElementById('root')).render(
  <MyApp />
);

翻译自:https://www.30secondsofcode.org/react/s/use-isomporphic-effect