Files
30-seconds-of-code/snippets/useIsomporphicEffect.md
2021-09-05 18:37:22 +03:00

616 B

title, tags, firstSeen
title tags firstSeen
useIsomporphicEffect hooks,effect,beginner 2021-09-29T05:00:00-04:00

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

  • Use typeof to check if the window object is defined and return the useLayoutEffect() if it is, or useEffect() otherwise.
const useIsomorphicEffect =
  typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;
const MyApp = () => {
  useIsomorphicEffect(() => {
    window.console.log('Hello');
  }, []);

  return null;
};

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